Add PendingOutboundPayment::InvoiceReceived
[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_drop_messages_peer_disconnect_dual_htlc() {
4085         // Test that we can handle reconnecting when both sides of a channel have pending
4086         // commitment_updates when we disconnect.
4087         let chanmon_cfgs = create_chanmon_cfgs(2);
4088         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4089         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4090         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4091         create_announced_chan_between_nodes(&nodes, 0, 1);
4092
4093         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
4094
4095         // Now try to send a second payment which will fail to send
4096         let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
4097         nodes[0].node.send_payment_with_route(&route, payment_hash_2,
4098                 RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
4099         check_added_monitors!(nodes[0], 1);
4100
4101         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
4102         assert_eq!(events_1.len(), 1);
4103         match events_1[0] {
4104                 MessageSendEvent::UpdateHTLCs { .. } => {},
4105                 _ => panic!("Unexpected event"),
4106         }
4107
4108         nodes[1].node.claim_funds(payment_preimage_1);
4109         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
4110         check_added_monitors!(nodes[1], 1);
4111
4112         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
4113         assert_eq!(events_2.len(), 1);
4114         match events_2[0] {
4115                 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 } } => {
4116                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
4117                         assert!(update_add_htlcs.is_empty());
4118                         assert_eq!(update_fulfill_htlcs.len(), 1);
4119                         assert!(update_fail_htlcs.is_empty());
4120                         assert!(update_fail_malformed_htlcs.is_empty());
4121                         assert!(update_fee.is_none());
4122
4123                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
4124                         let events_3 = nodes[0].node.get_and_clear_pending_events();
4125                         assert_eq!(events_3.len(), 1);
4126                         match events_3[0] {
4127                                 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4128                                         assert_eq!(*payment_preimage, payment_preimage_1);
4129                                         assert_eq!(*payment_hash, payment_hash_1);
4130                                 },
4131                                 _ => panic!("Unexpected event"),
4132                         }
4133
4134                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
4135                         let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4136                         // No commitment_signed so get_event_msg's assert(len == 1) passes
4137                         check_added_monitors!(nodes[0], 1);
4138                 },
4139                 _ => panic!("Unexpected event"),
4140         }
4141
4142         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
4143         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
4144
4145         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
4146                 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
4147         }, true).unwrap();
4148         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4149         assert_eq!(reestablish_1.len(), 1);
4150         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
4151                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
4152         }, false).unwrap();
4153         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4154         assert_eq!(reestablish_2.len(), 1);
4155
4156         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4157         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4158         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4159         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4160
4161         assert!(as_resp.0.is_none());
4162         assert!(bs_resp.0.is_none());
4163
4164         assert!(bs_resp.1.is_none());
4165         assert!(bs_resp.2.is_none());
4166
4167         assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4168
4169         assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4170         assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4171         assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4172         assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4173         assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4174         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4175         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4176         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4177         // No commitment_signed so get_event_msg's assert(len == 1) passes
4178         check_added_monitors!(nodes[1], 1);
4179
4180         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4181         let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4182         assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4183         assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4184         assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4185         assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4186         assert!(bs_second_commitment_signed.update_fee.is_none());
4187         check_added_monitors!(nodes[1], 1);
4188
4189         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4190         let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4191         assert!(as_commitment_signed.update_add_htlcs.is_empty());
4192         assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4193         assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4194         assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4195         assert!(as_commitment_signed.update_fee.is_none());
4196         check_added_monitors!(nodes[0], 1);
4197
4198         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4199         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4200         // No commitment_signed so get_event_msg's assert(len == 1) passes
4201         check_added_monitors!(nodes[0], 1);
4202
4203         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4204         let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4205         // No commitment_signed so get_event_msg's assert(len == 1) passes
4206         check_added_monitors!(nodes[1], 1);
4207
4208         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4209         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4210         check_added_monitors!(nodes[1], 1);
4211
4212         expect_pending_htlcs_forwardable!(nodes[1]);
4213
4214         let events_5 = nodes[1].node.get_and_clear_pending_events();
4215         assert_eq!(events_5.len(), 1);
4216         match events_5[0] {
4217                 Event::PaymentClaimable { ref payment_hash, ref purpose, .. } => {
4218                         assert_eq!(payment_hash_2, *payment_hash);
4219                         match &purpose {
4220                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4221                                         assert!(payment_preimage.is_none());
4222                                         assert_eq!(payment_secret_2, *payment_secret);
4223                                 },
4224                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
4225                         }
4226                 },
4227                 _ => panic!("Unexpected event"),
4228         }
4229
4230         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4231         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4232         check_added_monitors!(nodes[0], 1);
4233
4234         expect_payment_path_successful!(nodes[0]);
4235         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4236 }
4237
4238 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4239         // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4240         // to avoid our counterparty failing the channel.
4241         let chanmon_cfgs = create_chanmon_cfgs(2);
4242         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4243         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4244         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4245
4246         create_announced_chan_between_nodes(&nodes, 0, 1);
4247
4248         let our_payment_hash = if send_partial_mpp {
4249                 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4250                 // Use the utility function send_payment_along_path to send the payment with MPP data which
4251                 // indicates there are more HTLCs coming.
4252                 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.
4253                 let payment_id = PaymentId([42; 32]);
4254                 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
4255                         RecipientOnionFields::secret_only(payment_secret), payment_id, &route).unwrap();
4256                 nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
4257                         RecipientOnionFields::secret_only(payment_secret), 200_000, cur_height, payment_id,
4258                         &None, session_privs[0]).unwrap();
4259                 check_added_monitors!(nodes[0], 1);
4260                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4261                 assert_eq!(events.len(), 1);
4262                 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4263                 // hop should *not* yet generate any PaymentClaimable event(s).
4264                 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4265                 our_payment_hash
4266         } else {
4267                 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4268         };
4269
4270         let mut block = create_dummy_block(nodes[0].best_block_hash(), 42, Vec::new());
4271         connect_block(&nodes[0], &block);
4272         connect_block(&nodes[1], &block);
4273         let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4274         for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4275                 block.header.prev_blockhash = block.block_hash();
4276                 connect_block(&nodes[0], &block);
4277                 connect_block(&nodes[1], &block);
4278         }
4279
4280         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
4281
4282         check_added_monitors!(nodes[1], 1);
4283         let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4284         assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4285         assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4286         assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4287         assert!(htlc_timeout_updates.update_fee.is_none());
4288
4289         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4290         commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4291         // 100_000 msat as u64, followed by the height at which we failed back above
4292         let mut expected_failure_data = (100_000 as u64).to_be_bytes().to_vec();
4293         expected_failure_data.extend_from_slice(&(block_count - 1).to_be_bytes());
4294         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4295 }
4296
4297 #[test]
4298 fn test_htlc_timeout() {
4299         do_test_htlc_timeout(true);
4300         do_test_htlc_timeout(false);
4301 }
4302
4303 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4304         // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4305         let chanmon_cfgs = create_chanmon_cfgs(3);
4306         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4307         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4308         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4309         create_announced_chan_between_nodes(&nodes, 0, 1);
4310         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4311
4312         // Make sure all nodes are at the same starting height
4313         connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4314         connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4315         connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4316
4317         // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4318         let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4319         nodes[1].node.send_payment_with_route(&route, first_payment_hash,
4320                 RecipientOnionFields::secret_only(first_payment_secret), PaymentId(first_payment_hash.0)).unwrap();
4321         assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4322         check_added_monitors!(nodes[1], 1);
4323
4324         // Now attempt to route a second payment, which should be placed in the holding cell
4325         let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4326         let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4327         sending_node.node.send_payment_with_route(&route, second_payment_hash,
4328                 RecipientOnionFields::secret_only(second_payment_secret), PaymentId(second_payment_hash.0)).unwrap();
4329         if forwarded_htlc {
4330                 check_added_monitors!(nodes[0], 1);
4331                 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4332                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4333                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4334                 expect_pending_htlcs_forwardable!(nodes[1]);
4335         }
4336         check_added_monitors!(nodes[1], 0);
4337
4338         connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4339         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4340         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4341         connect_blocks(&nodes[1], 1);
4342
4343         if forwarded_htlc {
4344                 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 }]);
4345                 check_added_monitors!(nodes[1], 1);
4346                 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4347                 assert_eq!(fail_commit.len(), 1);
4348                 match fail_commit[0] {
4349                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4350                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4351                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4352                         },
4353                         _ => unreachable!(),
4354                 }
4355                 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4356         } else {
4357                 expect_payment_failed!(nodes[1], second_payment_hash, false);
4358         }
4359 }
4360
4361 #[test]
4362 fn test_holding_cell_htlc_add_timeouts() {
4363         do_test_holding_cell_htlc_add_timeouts(false);
4364         do_test_holding_cell_htlc_add_timeouts(true);
4365 }
4366
4367 macro_rules! check_spendable_outputs {
4368         ($node: expr, $keysinterface: expr) => {
4369                 {
4370                         let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4371                         let mut txn = Vec::new();
4372                         let mut all_outputs = Vec::new();
4373                         let secp_ctx = Secp256k1::new();
4374                         for event in events.drain(..) {
4375                                 match event {
4376                                         Event::SpendableOutputs { mut outputs, channel_id: _ } => {
4377                                                 for outp in outputs.drain(..) {
4378                                                         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());
4379                                                         all_outputs.push(outp);
4380                                                 }
4381                                         },
4382                                         _ => panic!("Unexpected event"),
4383                                 };
4384                         }
4385                         if all_outputs.len() > 1 {
4386                                 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) {
4387                                         txn.push(tx);
4388                                 }
4389                         }
4390                         txn
4391                 }
4392         }
4393 }
4394
4395 #[test]
4396 fn test_claim_sizeable_push_msat() {
4397         // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4398         let chanmon_cfgs = create_chanmon_cfgs(2);
4399         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4400         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4401         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4402
4403         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4404         nodes[1].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
4405         check_closed_broadcast!(nodes[1], true);
4406         check_added_monitors!(nodes[1], 1);
4407         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[0].node.get_our_node_id()], 100000);
4408         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4409         assert_eq!(node_txn.len(), 1);
4410         check_spends!(node_txn[0], chan.3);
4411         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
4412
4413         mine_transaction(&nodes[1], &node_txn[0]);
4414         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4415
4416         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4417         assert_eq!(spend_txn.len(), 1);
4418         assert_eq!(spend_txn[0].input.len(), 1);
4419         check_spends!(spend_txn[0], node_txn[0]);
4420         assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4421 }
4422
4423 #[test]
4424 fn test_claim_on_remote_sizeable_push_msat() {
4425         // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4426         // to_remote output is encumbered by a P2WPKH
4427         let chanmon_cfgs = create_chanmon_cfgs(2);
4428         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4429         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4430         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4431
4432         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4433         nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
4434         check_closed_broadcast!(nodes[0], true);
4435         check_added_monitors!(nodes[0], 1);
4436         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
4437
4438         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4439         assert_eq!(node_txn.len(), 1);
4440         check_spends!(node_txn[0], chan.3);
4441         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
4442
4443         mine_transaction(&nodes[1], &node_txn[0]);
4444         check_closed_broadcast!(nodes[1], true);
4445         check_added_monitors!(nodes[1], 1);
4446         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4447         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4448
4449         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4450         assert_eq!(spend_txn.len(), 1);
4451         check_spends!(spend_txn[0], node_txn[0]);
4452 }
4453
4454 #[test]
4455 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4456         // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4457         // to_remote output is encumbered by a P2WPKH
4458
4459         let chanmon_cfgs = create_chanmon_cfgs(2);
4460         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4461         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4462         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4463
4464         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000);
4465         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4466         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4467         assert_eq!(revoked_local_txn[0].input.len(), 1);
4468         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4469
4470         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4471         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4472         check_closed_broadcast!(nodes[1], true);
4473         check_added_monitors!(nodes[1], 1);
4474         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4475
4476         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4477         mine_transaction(&nodes[1], &node_txn[0]);
4478         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4479
4480         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4481         assert_eq!(spend_txn.len(), 3);
4482         check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4483         check_spends!(spend_txn[1], node_txn[0]);
4484         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4485 }
4486
4487 #[test]
4488 fn test_static_spendable_outputs_preimage_tx() {
4489         let chanmon_cfgs = create_chanmon_cfgs(2);
4490         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4491         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4492         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4493
4494         // Create some initial channels
4495         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4496
4497         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
4498
4499         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4500         assert_eq!(commitment_tx[0].input.len(), 1);
4501         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4502
4503         // Settle A's commitment tx on B's chain
4504         nodes[1].node.claim_funds(payment_preimage);
4505         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
4506         check_added_monitors!(nodes[1], 1);
4507         mine_transaction(&nodes[1], &commitment_tx[0]);
4508         check_added_monitors!(nodes[1], 1);
4509         let events = nodes[1].node.get_and_clear_pending_msg_events();
4510         match events[0] {
4511                 MessageSendEvent::UpdateHTLCs { .. } => {},
4512                 _ => panic!("Unexpected event"),
4513         }
4514         match events[1] {
4515                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4516                 _ => panic!("Unexepected event"),
4517         }
4518
4519         // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4520         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: preimage tx
4521         assert_eq!(node_txn.len(), 1);
4522         check_spends!(node_txn[0], commitment_tx[0]);
4523         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4524
4525         mine_transaction(&nodes[1], &node_txn[0]);
4526         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4527         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4528
4529         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4530         assert_eq!(spend_txn.len(), 1);
4531         check_spends!(spend_txn[0], node_txn[0]);
4532 }
4533
4534 #[test]
4535 fn test_static_spendable_outputs_timeout_tx() {
4536         let chanmon_cfgs = create_chanmon_cfgs(2);
4537         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4538         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4539         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4540
4541         // Create some initial channels
4542         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4543
4544         // Rebalance the network a bit by relaying one payment through all the channels ...
4545         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4546
4547         let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4548
4549         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4550         assert_eq!(commitment_tx[0].input.len(), 1);
4551         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4552
4553         // Settle A's commitment tx on B' chain
4554         mine_transaction(&nodes[1], &commitment_tx[0]);
4555         check_added_monitors!(nodes[1], 1);
4556         let events = nodes[1].node.get_and_clear_pending_msg_events();
4557         match events[0] {
4558                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4559                 _ => panic!("Unexpected event"),
4560         }
4561         connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
4562
4563         // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4564         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4565         assert_eq!(node_txn.len(), 1); // ChannelMonitor: timeout tx
4566         check_spends!(node_txn[0],  commitment_tx[0].clone());
4567         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4568
4569         mine_transaction(&nodes[1], &node_txn[0]);
4570         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4571         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4572         expect_payment_failed!(nodes[1], our_payment_hash, false);
4573
4574         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4575         assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4576         check_spends!(spend_txn[0], commitment_tx[0]);
4577         check_spends!(spend_txn[1], node_txn[0]);
4578         check_spends!(spend_txn[2], node_txn[0], commitment_tx[0]); // All outputs
4579 }
4580
4581 #[test]
4582 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4583         let chanmon_cfgs = create_chanmon_cfgs(2);
4584         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4585         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4586         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4587
4588         // Create some initial channels
4589         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4590
4591         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4592         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4593         assert_eq!(revoked_local_txn[0].input.len(), 1);
4594         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4595
4596         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4597
4598         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4599         check_closed_broadcast!(nodes[1], true);
4600         check_added_monitors!(nodes[1], 1);
4601         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4602
4603         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4604         assert_eq!(node_txn.len(), 1);
4605         assert_eq!(node_txn[0].input.len(), 2);
4606         check_spends!(node_txn[0], revoked_local_txn[0]);
4607
4608         mine_transaction(&nodes[1], &node_txn[0]);
4609         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4610
4611         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4612         assert_eq!(spend_txn.len(), 1);
4613         check_spends!(spend_txn[0], node_txn[0]);
4614 }
4615
4616 #[test]
4617 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4618         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4619         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4620         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4621         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4622         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4623
4624         // Create some initial channels
4625         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4626
4627         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4628         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4629         assert_eq!(revoked_local_txn[0].input.len(), 1);
4630         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4631
4632         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4633
4634         // A will generate HTLC-Timeout from revoked commitment tx
4635         mine_transaction(&nodes[0], &revoked_local_txn[0]);
4636         check_closed_broadcast!(nodes[0], true);
4637         check_added_monitors!(nodes[0], 1);
4638         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
4639         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
4640
4641         let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4642         assert_eq!(revoked_htlc_txn.len(), 1);
4643         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4644         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4645         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4646         assert_ne!(revoked_htlc_txn[0].lock_time.0, 0); // HTLC-Timeout
4647
4648         // B will generate justice tx from A's revoked commitment/HTLC tx
4649         connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()]));
4650         check_closed_broadcast!(nodes[1], true);
4651         check_added_monitors!(nodes[1], 1);
4652         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4653
4654         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4655         assert_eq!(node_txn.len(), 2); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs
4656         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4657         // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
4658         // transactions next...
4659         assert_eq!(node_txn[0].input.len(), 3);
4660         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4661
4662         assert_eq!(node_txn[1].input.len(), 2);
4663         check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[0]);
4664         if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4665                 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4666         } else {
4667                 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4668                 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4669         }
4670
4671         mine_transaction(&nodes[1], &node_txn[1]);
4672         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4673
4674         // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4675         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4676         assert_eq!(spend_txn.len(), 1);
4677         assert_eq!(spend_txn[0].input.len(), 1);
4678         check_spends!(spend_txn[0], node_txn[1]);
4679 }
4680
4681 #[test]
4682 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4683         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4684         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4685         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4686         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4687         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4688
4689         // Create some initial channels
4690         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4691
4692         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4693         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4694         assert_eq!(revoked_local_txn[0].input.len(), 1);
4695         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4696
4697         // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4698         assert_eq!(revoked_local_txn[0].output.len(), 2);
4699
4700         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4701
4702         // B will generate HTLC-Success from revoked commitment tx
4703         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4704         check_closed_broadcast!(nodes[1], true);
4705         check_added_monitors!(nodes[1], 1);
4706         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4707         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4708
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(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4712         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4713
4714         // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
4715         let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
4716         assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
4717
4718         // A will generate justice tx from B's revoked commitment/HTLC tx
4719         connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()]));
4720         check_closed_broadcast!(nodes[0], true);
4721         check_added_monitors!(nodes[0], 1);
4722         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
4723
4724         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4725         assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success
4726
4727         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4728         // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4729         // transactions next...
4730         assert_eq!(node_txn[0].input.len(), 2);
4731         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4732         if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4733                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4734         } else {
4735                 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4736                 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4737         }
4738
4739         assert_eq!(node_txn[1].input.len(), 1);
4740         check_spends!(node_txn[1], revoked_htlc_txn[0]);
4741
4742         mine_transaction(&nodes[0], &node_txn[1]);
4743         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
4744
4745         // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
4746         // didn't try to generate any new transactions.
4747
4748         // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4749         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
4750         assert_eq!(spend_txn.len(), 3);
4751         assert_eq!(spend_txn[0].input.len(), 1);
4752         check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
4753         assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4754         check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
4755         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
4756 }
4757
4758 #[test]
4759 fn test_onchain_to_onchain_claim() {
4760         // Test that in case of channel closure, we detect the state of output and claim HTLC
4761         // on downstream peer's remote commitment tx.
4762         // First, have C claim an HTLC against its own latest commitment transaction.
4763         // Then, broadcast these to B, which should update the monitor downstream on the A<->B
4764         // channel.
4765         // Finally, check that B will claim the HTLC output if A's latest commitment transaction
4766         // gets broadcast.
4767
4768         let chanmon_cfgs = create_chanmon_cfgs(3);
4769         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4770         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4771         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4772
4773         // Create some initial channels
4774         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4775         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4776
4777         // Ensure all nodes are at the same height
4778         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4779         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4780         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4781         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4782
4783         // Rebalance the network a bit by relaying one payment through all the channels ...
4784         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4785         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4786
4787         let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
4788         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
4789         check_spends!(commitment_tx[0], chan_2.3);
4790         nodes[2].node.claim_funds(payment_preimage);
4791         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
4792         check_added_monitors!(nodes[2], 1);
4793         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4794         assert!(updates.update_add_htlcs.is_empty());
4795         assert!(updates.update_fail_htlcs.is_empty());
4796         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4797         assert!(updates.update_fail_malformed_htlcs.is_empty());
4798
4799         mine_transaction(&nodes[2], &commitment_tx[0]);
4800         check_closed_broadcast!(nodes[2], true);
4801         check_added_monitors!(nodes[2], 1);
4802         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
4803
4804         let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 1 (HTLC-Success tx)
4805         assert_eq!(c_txn.len(), 1);
4806         check_spends!(c_txn[0], commitment_tx[0]);
4807         assert_eq!(c_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4808         assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4809         assert_eq!(c_txn[0].lock_time.0, 0); // Success tx
4810
4811         // 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
4812         connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![commitment_tx[0].clone(), c_txn[0].clone()]));
4813         check_added_monitors!(nodes[1], 1);
4814         let events = nodes[1].node.get_and_clear_pending_events();
4815         assert_eq!(events.len(), 2);
4816         match events[0] {
4817                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
4818                 _ => panic!("Unexpected event"),
4819         }
4820         match events[1] {
4821                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
4822                         assert_eq!(fee_earned_msat, Some(1000));
4823                         assert_eq!(prev_channel_id, Some(chan_1.2));
4824                         assert_eq!(claim_from_onchain_tx, true);
4825                         assert_eq!(next_channel_id, Some(chan_2.2));
4826                         assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
4827                 },
4828                 _ => panic!("Unexpected event"),
4829         }
4830         check_added_monitors!(nodes[1], 1);
4831         let mut msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4832         assert_eq!(msg_events.len(), 3);
4833         let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut msg_events);
4834         let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut msg_events);
4835
4836         match nodes_2_event {
4837                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
4838                 _ => panic!("Unexpected event"),
4839         }
4840
4841         match nodes_0_event {
4842                 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, .. } } => {
4843                         assert!(update_add_htlcs.is_empty());
4844                         assert!(update_fail_htlcs.is_empty());
4845                         assert_eq!(update_fulfill_htlcs.len(), 1);
4846                         assert!(update_fail_malformed_htlcs.is_empty());
4847                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
4848                 },
4849                 _ => panic!("Unexpected event"),
4850         };
4851
4852         // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
4853         match msg_events[0] {
4854                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4855                 _ => panic!("Unexpected event"),
4856         }
4857
4858         // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
4859         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4860         mine_transaction(&nodes[1], &commitment_tx[0]);
4861         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4862         let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4863         // ChannelMonitor: HTLC-Success tx
4864         assert_eq!(b_txn.len(), 1);
4865         check_spends!(b_txn[0], commitment_tx[0]);
4866         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4867         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4868         assert_eq!(b_txn[0].lock_time.0, nodes[1].best_block_info().1); // Success tx
4869
4870         check_closed_broadcast!(nodes[1], true);
4871         check_added_monitors!(nodes[1], 1);
4872 }
4873
4874 #[test]
4875 fn test_duplicate_payment_hash_one_failure_one_success() {
4876         // Topology : A --> B --> C --> D
4877         // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
4878         // Note that because C will refuse to generate two payment secrets for the same payment hash,
4879         // we forward one of the payments onwards to D.
4880         let chanmon_cfgs = create_chanmon_cfgs(4);
4881         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4882         // When this test was written, the default base fee floated based on the HTLC count.
4883         // It is now fixed, so we simply set the fee to the expected value here.
4884         let mut config = test_default_channel_config();
4885         config.channel_config.forwarding_fee_base_msat = 196;
4886         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
4887                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4888         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4889
4890         create_announced_chan_between_nodes(&nodes, 0, 1);
4891         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4892         create_announced_chan_between_nodes(&nodes, 2, 3);
4893
4894         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4895         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4896         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4897         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4898         connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
4899
4900         let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 900_000);
4901
4902         let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200, None).unwrap();
4903         // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
4904         // script push size limit so that the below script length checks match
4905         // ACCEPTED_HTLC_SCRIPT_WEIGHT.
4906         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV - 40)
4907                 .with_bolt11_features(nodes[3].node.invoice_features()).unwrap();
4908         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 800_000);
4909         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 800_000, duplicate_payment_hash, payment_secret);
4910
4911         let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
4912         assert_eq!(commitment_txn[0].input.len(), 1);
4913         check_spends!(commitment_txn[0], chan_2.3);
4914
4915         mine_transaction(&nodes[1], &commitment_txn[0]);
4916         check_closed_broadcast!(nodes[1], true);
4917         check_added_monitors!(nodes[1], 1);
4918         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[2].node.get_our_node_id()], 100000);
4919         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
4920
4921         let htlc_timeout_tx;
4922         { // Extract one of the two HTLC-Timeout transaction
4923                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4924                 // ChannelMonitor: timeout tx * 2-or-3
4925                 assert!(node_txn.len() == 2 || node_txn.len() == 3);
4926
4927                 check_spends!(node_txn[0], commitment_txn[0]);
4928                 assert_eq!(node_txn[0].input.len(), 1);
4929                 assert_eq!(node_txn[0].output.len(), 1);
4930
4931                 if node_txn.len() > 2 {
4932                         check_spends!(node_txn[1], commitment_txn[0]);
4933                         assert_eq!(node_txn[1].input.len(), 1);
4934                         assert_eq!(node_txn[1].output.len(), 1);
4935                         assert_eq!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
4936
4937                         check_spends!(node_txn[2], commitment_txn[0]);
4938                         assert_eq!(node_txn[2].input.len(), 1);
4939                         assert_eq!(node_txn[2].output.len(), 1);
4940                         assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
4941                 } else {
4942                         check_spends!(node_txn[1], commitment_txn[0]);
4943                         assert_eq!(node_txn[1].input.len(), 1);
4944                         assert_eq!(node_txn[1].output.len(), 1);
4945                         assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
4946                 }
4947
4948                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4949                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4950                 // Assign htlc_timeout_tx to the forwarded HTLC (with value ~800 sats). The received HTLC
4951                 // (with value 900 sats) will be claimed in the below `claim_funds` call.
4952                 if node_txn.len() > 2 {
4953                         assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4954                         htlc_timeout_tx = if node_txn[2].output[0].value < 900 { node_txn[2].clone() } else { node_txn[0].clone() };
4955                 } else {
4956                         htlc_timeout_tx = if node_txn[0].output[0].value < 900 { node_txn[1].clone() } else { node_txn[0].clone() };
4957                 }
4958         }
4959
4960         nodes[2].node.claim_funds(our_payment_preimage);
4961         expect_payment_claimed!(nodes[2], duplicate_payment_hash, 900_000);
4962
4963         mine_transaction(&nodes[2], &commitment_txn[0]);
4964         check_added_monitors!(nodes[2], 2);
4965         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
4966         let events = nodes[2].node.get_and_clear_pending_msg_events();
4967         match events[0] {
4968                 MessageSendEvent::UpdateHTLCs { .. } => {},
4969                 _ => panic!("Unexpected event"),
4970         }
4971         match events[1] {
4972                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4973                 _ => panic!("Unexepected event"),
4974         }
4975         let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4976         assert_eq!(htlc_success_txn.len(), 2); // ChannelMonitor: HTLC-Success txn (*2 due to 2-HTLC outputs)
4977         check_spends!(htlc_success_txn[0], commitment_txn[0]);
4978         check_spends!(htlc_success_txn[1], commitment_txn[0]);
4979         assert_eq!(htlc_success_txn[0].input.len(), 1);
4980         assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4981         assert_eq!(htlc_success_txn[1].input.len(), 1);
4982         assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4983         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
4984         assert_ne!(htlc_success_txn[1].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
4985
4986         mine_transaction(&nodes[1], &htlc_timeout_tx);
4987         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4988         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 }]);
4989         let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4990         assert!(htlc_updates.update_add_htlcs.is_empty());
4991         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
4992         let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
4993         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
4994         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
4995         check_added_monitors!(nodes[1], 1);
4996
4997         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
4998         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4999         {
5000                 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5001         }
5002         expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
5003
5004         // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5005         mine_transaction(&nodes[1], &htlc_success_txn[1]);
5006         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196), true, true);
5007         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5008         assert!(updates.update_add_htlcs.is_empty());
5009         assert!(updates.update_fail_htlcs.is_empty());
5010         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5011         assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
5012         assert!(updates.update_fail_malformed_htlcs.is_empty());
5013         check_added_monitors!(nodes[1], 1);
5014
5015         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5016         commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5017         expect_payment_sent(&nodes[0], our_payment_preimage, None, true, true);
5018 }
5019
5020 #[test]
5021 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5022         let chanmon_cfgs = create_chanmon_cfgs(2);
5023         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5024         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5025         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5026
5027         // Create some initial channels
5028         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5029
5030         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
5031         let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5032         assert_eq!(local_txn.len(), 1);
5033         assert_eq!(local_txn[0].input.len(), 1);
5034         check_spends!(local_txn[0], chan_1.3);
5035
5036         // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5037         nodes[1].node.claim_funds(payment_preimage);
5038         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
5039         check_added_monitors!(nodes[1], 1);
5040
5041         mine_transaction(&nodes[1], &local_txn[0]);
5042         check_added_monitors!(nodes[1], 1);
5043         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
5044         let events = nodes[1].node.get_and_clear_pending_msg_events();
5045         match events[0] {
5046                 MessageSendEvent::UpdateHTLCs { .. } => {},
5047                 _ => panic!("Unexpected event"),
5048         }
5049         match events[1] {
5050                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5051                 _ => panic!("Unexepected event"),
5052         }
5053         let node_tx = {
5054                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5055                 assert_eq!(node_txn.len(), 1);
5056                 assert_eq!(node_txn[0].input.len(), 1);
5057                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5058                 check_spends!(node_txn[0], local_txn[0]);
5059                 node_txn[0].clone()
5060         };
5061
5062         mine_transaction(&nodes[1], &node_tx);
5063         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
5064
5065         // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5066         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5067         assert_eq!(spend_txn.len(), 1);
5068         assert_eq!(spend_txn[0].input.len(), 1);
5069         check_spends!(spend_txn[0], node_tx);
5070         assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5071 }
5072
5073 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5074         // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5075         // unrevoked commitment transaction.
5076         // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5077         // a remote RAA before they could be failed backwards (and combinations thereof).
5078         // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5079         // use the same payment hashes.
5080         // Thus, we use a six-node network:
5081         //
5082         // A \         / E
5083         //    - C - D -
5084         // B /         \ F
5085         // And test where C fails back to A/B when D announces its latest commitment transaction
5086         let chanmon_cfgs = create_chanmon_cfgs(6);
5087         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5088         // When this test was written, the default base fee floated based on the HTLC count.
5089         // It is now fixed, so we simply set the fee to the expected value here.
5090         let mut config = test_default_channel_config();
5091         config.channel_config.forwarding_fee_base_msat = 196;
5092         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
5093                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5094         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5095
5096         let _chan_0_2 = create_announced_chan_between_nodes(&nodes, 0, 2);
5097         let _chan_1_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5098         let chan_2_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
5099         let chan_3_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
5100         let chan_3_5  = create_announced_chan_between_nodes(&nodes, 3, 5);
5101
5102         // Rebalance and check output sanity...
5103         send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
5104         send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
5105         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 2);
5106
5107         let ds_dust_limit = nodes[3].node.per_peer_state.read().unwrap().get(&nodes[2].node.get_our_node_id())
5108                 .unwrap().lock().unwrap().channel_by_id.get(&chan_2_3.2).unwrap().context.holder_dust_limit_satoshis;
5109         // 0th HTLC:
5110         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
5111         // 1st HTLC:
5112         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
5113         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5114         // 2nd HTLC:
5115         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
5116         // 3rd HTLC:
5117         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
5118         // 4th HTLC:
5119         let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5120         // 5th HTLC:
5121         let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5122         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5123         // 6th HTLC:
5124         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());
5125         // 7th HTLC:
5126         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());
5127
5128         // 8th HTLC:
5129         let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5130         // 9th HTLC:
5131         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5132         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
5133
5134         // 10th HTLC:
5135         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
5136         // 11th HTLC:
5137         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5138         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());
5139
5140         // Double-check that six of the new HTLC were added
5141         // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5142         // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5143         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2).len(), 1);
5144         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 8);
5145
5146         // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5147         // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5148         nodes[4].node.fail_htlc_backwards(&payment_hash_1);
5149         nodes[4].node.fail_htlc_backwards(&payment_hash_3);
5150         nodes[4].node.fail_htlc_backwards(&payment_hash_5);
5151         nodes[4].node.fail_htlc_backwards(&payment_hash_6);
5152         check_added_monitors!(nodes[4], 0);
5153
5154         let failed_destinations = vec![
5155                 HTLCDestination::FailedPayment { payment_hash: payment_hash_1 },
5156                 HTLCDestination::FailedPayment { payment_hash: payment_hash_3 },
5157                 HTLCDestination::FailedPayment { payment_hash: payment_hash_5 },
5158                 HTLCDestination::FailedPayment { payment_hash: payment_hash_6 },
5159         ];
5160         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[4], failed_destinations);
5161         check_added_monitors!(nodes[4], 1);
5162
5163         let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5164         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5165         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5166         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5167         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5168         commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5169
5170         // Fail 3rd below-dust and 7th above-dust HTLCs
5171         nodes[5].node.fail_htlc_backwards(&payment_hash_2);
5172         nodes[5].node.fail_htlc_backwards(&payment_hash_4);
5173         check_added_monitors!(nodes[5], 0);
5174
5175         let failed_destinations_2 = vec![
5176                 HTLCDestination::FailedPayment { payment_hash: payment_hash_2 },
5177                 HTLCDestination::FailedPayment { payment_hash: payment_hash_4 },
5178         ];
5179         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[5], failed_destinations_2);
5180         check_added_monitors!(nodes[5], 1);
5181
5182         let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5183         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5184         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5185         commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5186
5187         let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5188
5189         // After 4 and 2 removes respectively above in nodes[4] and nodes[5], nodes[3] should receive 6 PaymentForwardedFailed events
5190         let failed_destinations_3 = vec![
5191                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5192                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5193                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5194                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5195                 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5196                 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5197         ];
5198         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations_3);
5199         check_added_monitors!(nodes[3], 1);
5200         let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5201         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5202         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5203         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5204         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5205         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5206         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5207         if deliver_last_raa {
5208                 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5209         } else {
5210                 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5211         }
5212
5213         // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5214         // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5215         // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5216         // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5217         //
5218         // We now broadcast the latest commitment transaction, which *should* result in failures for
5219         // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5220         // the non-broadcast above-dust HTLCs.
5221         //
5222         // Alternatively, we may broadcast the previous commitment transaction, which should only
5223         // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5224         let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5225
5226         if announce_latest {
5227                 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5228         } else {
5229                 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5230         }
5231         let events = nodes[2].node.get_and_clear_pending_events();
5232         let close_event = if deliver_last_raa {
5233                 assert_eq!(events.len(), 2 + 6);
5234                 events.last().clone().unwrap()
5235         } else {
5236                 assert_eq!(events.len(), 1);
5237                 events.last().clone().unwrap()
5238         };
5239         match close_event {
5240                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5241                 _ => panic!("Unexpected event"),
5242         }
5243
5244         connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5245         check_closed_broadcast!(nodes[2], true);
5246         if deliver_last_raa {
5247                 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5248
5249                 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();
5250                 expect_htlc_handling_failed_destinations!(nodes[2].node.get_and_clear_pending_events(), expected_destinations);
5251         } else {
5252                 let expected_destinations: Vec<HTLCDestination> = if announce_latest {
5253                         repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(9).collect()
5254                 } else {
5255                         repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(6).collect()
5256                 };
5257
5258                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], expected_destinations);
5259         }
5260         check_added_monitors!(nodes[2], 3);
5261
5262         let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5263         assert_eq!(cs_msgs.len(), 2);
5264         let mut a_done = false;
5265         for msg in cs_msgs {
5266                 match msg {
5267                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5268                                 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5269                                 // should be failed-backwards here.
5270                                 let target = if *node_id == nodes[0].node.get_our_node_id() {
5271                                         // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5272                                         for htlc in &updates.update_fail_htlcs {
5273                                                 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 });
5274                                         }
5275                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5276                                         assert!(!a_done);
5277                                         a_done = true;
5278                                         &nodes[0]
5279                                 } else {
5280                                         // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5281                                         for htlc in &updates.update_fail_htlcs {
5282                                                 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5283                                         }
5284                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5285                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5286                                         &nodes[1]
5287                                 };
5288                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5289                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5290                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5291                                 if announce_latest {
5292                                         target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5293                                         if *node_id == nodes[0].node.get_our_node_id() {
5294                                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5295                                         }
5296                                 }
5297                                 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5298                         },
5299                         _ => panic!("Unexpected event"),
5300                 }
5301         }
5302
5303         let as_events = nodes[0].node.get_and_clear_pending_events();
5304         assert_eq!(as_events.len(), if announce_latest { 10 } else { 6 });
5305         let mut as_failds = HashSet::new();
5306         let mut as_updates = 0;
5307         for event in as_events.iter() {
5308                 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5309                         assert!(as_failds.insert(*payment_hash));
5310                         if *payment_hash != payment_hash_2 {
5311                                 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5312                         } else {
5313                                 assert!(!payment_failed_permanently);
5314                         }
5315                         if let PathFailure::OnPath { network_update: Some(_) } = failure {
5316                                 as_updates += 1;
5317                         }
5318                 } else if let &Event::PaymentFailed { .. } = event {
5319                 } else { panic!("Unexpected event"); }
5320         }
5321         assert!(as_failds.contains(&payment_hash_1));
5322         assert!(as_failds.contains(&payment_hash_2));
5323         if announce_latest {
5324                 assert!(as_failds.contains(&payment_hash_3));
5325                 assert!(as_failds.contains(&payment_hash_5));
5326         }
5327         assert!(as_failds.contains(&payment_hash_6));
5328
5329         let bs_events = nodes[1].node.get_and_clear_pending_events();
5330         assert_eq!(bs_events.len(), if announce_latest { 8 } else { 6 });
5331         let mut bs_failds = HashSet::new();
5332         let mut bs_updates = 0;
5333         for event in bs_events.iter() {
5334                 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5335                         assert!(bs_failds.insert(*payment_hash));
5336                         if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5337                                 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5338                         } else {
5339                                 assert!(!payment_failed_permanently);
5340                         }
5341                         if let PathFailure::OnPath { network_update: Some(_) } = failure {
5342                                 bs_updates += 1;
5343                         }
5344                 } else if let &Event::PaymentFailed { .. } = event {
5345                 } else { panic!("Unexpected event"); }
5346         }
5347         assert!(bs_failds.contains(&payment_hash_1));
5348         assert!(bs_failds.contains(&payment_hash_2));
5349         if announce_latest {
5350                 assert!(bs_failds.contains(&payment_hash_4));
5351         }
5352         assert!(bs_failds.contains(&payment_hash_5));
5353
5354         // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5355         // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5356         // unknown-preimage-etc, B should have gotten 2. Thus, in the
5357         // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5358         assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5359         assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5360 }
5361
5362 #[test]
5363 fn test_fail_backwards_latest_remote_announce_a() {
5364         do_test_fail_backwards_unrevoked_remote_announce(false, true);
5365 }
5366
5367 #[test]
5368 fn test_fail_backwards_latest_remote_announce_b() {
5369         do_test_fail_backwards_unrevoked_remote_announce(true, true);
5370 }
5371
5372 #[test]
5373 fn test_fail_backwards_previous_remote_announce() {
5374         do_test_fail_backwards_unrevoked_remote_announce(false, false);
5375         // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5376         // tested for in test_commitment_revoked_fail_backward_exhaustive()
5377 }
5378
5379 #[test]
5380 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5381         let chanmon_cfgs = create_chanmon_cfgs(2);
5382         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5383         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5384         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5385
5386         // Create some initial channels
5387         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5388
5389         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5390         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5391         assert_eq!(local_txn[0].input.len(), 1);
5392         check_spends!(local_txn[0], chan_1.3);
5393
5394         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5395         mine_transaction(&nodes[0], &local_txn[0]);
5396         check_closed_broadcast!(nodes[0], true);
5397         check_added_monitors!(nodes[0], 1);
5398         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
5399         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
5400
5401         let htlc_timeout = {
5402                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5403                 assert_eq!(node_txn.len(), 1);
5404                 assert_eq!(node_txn[0].input.len(), 1);
5405                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5406                 check_spends!(node_txn[0], local_txn[0]);
5407                 node_txn[0].clone()
5408         };
5409
5410         mine_transaction(&nodes[0], &htlc_timeout);
5411         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5412         expect_payment_failed!(nodes[0], our_payment_hash, false);
5413
5414         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5415         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5416         assert_eq!(spend_txn.len(), 3);
5417         check_spends!(spend_txn[0], local_txn[0]);
5418         assert_eq!(spend_txn[1].input.len(), 1);
5419         check_spends!(spend_txn[1], htlc_timeout);
5420         assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5421         assert_eq!(spend_txn[2].input.len(), 2);
5422         check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5423         assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5424                 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5425 }
5426
5427 #[test]
5428 fn test_key_derivation_params() {
5429         // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with a key
5430         // manager rotation to test that `channel_keys_id` returned in
5431         // [`SpendableOutputDescriptor::DelayedPaymentOutput`] let us re-derive the channel key set to
5432         // then derive a `delayed_payment_key`.
5433
5434         let chanmon_cfgs = create_chanmon_cfgs(3);
5435
5436         // We manually create the node configuration to backup the seed.
5437         let seed = [42; 32];
5438         let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5439         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);
5440         let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &chanmon_cfgs[0].logger));
5441         let scorer = RwLock::new(test_utils::TestScorer::new());
5442         let router = test_utils::TestRouter::new(network_graph.clone(), &scorer);
5443         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)) };
5444         let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5445         node_cfgs.remove(0);
5446         node_cfgs.insert(0, node);
5447
5448         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5449         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5450
5451         // Create some initial channels
5452         // Create a dummy channel to advance index by one and thus test re-derivation correctness
5453         // for node 0
5454         let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2);
5455         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5456         assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5457
5458         // Ensure all nodes are at the same height
5459         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5460         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5461         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5462         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5463
5464         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5465         let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5466         let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5467         assert_eq!(local_txn_1[0].input.len(), 1);
5468         check_spends!(local_txn_1[0], chan_1.3);
5469
5470         // We check funding pubkey are unique
5471         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]));
5472         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]));
5473         if from_0_funding_key_0 == from_1_funding_key_0
5474             || from_0_funding_key_0 == from_1_funding_key_1
5475             || from_0_funding_key_1 == from_1_funding_key_0
5476             || from_0_funding_key_1 == from_1_funding_key_1 {
5477                 panic!("Funding pubkeys aren't unique");
5478         }
5479
5480         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5481         mine_transaction(&nodes[0], &local_txn_1[0]);
5482         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
5483         check_closed_broadcast!(nodes[0], true);
5484         check_added_monitors!(nodes[0], 1);
5485         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
5486
5487         let htlc_timeout = {
5488                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5489                 assert_eq!(node_txn.len(), 1);
5490                 assert_eq!(node_txn[0].input.len(), 1);
5491                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5492                 check_spends!(node_txn[0], local_txn_1[0]);
5493                 node_txn[0].clone()
5494         };
5495
5496         mine_transaction(&nodes[0], &htlc_timeout);
5497         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5498         expect_payment_failed!(nodes[0], our_payment_hash, false);
5499
5500         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5501         let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5502         let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5503         assert_eq!(spend_txn.len(), 3);
5504         check_spends!(spend_txn[0], local_txn_1[0]);
5505         assert_eq!(spend_txn[1].input.len(), 1);
5506         check_spends!(spend_txn[1], htlc_timeout);
5507         assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5508         assert_eq!(spend_txn[2].input.len(), 2);
5509         check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5510         assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5511                 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5512 }
5513
5514 #[test]
5515 fn test_static_output_closing_tx() {
5516         let chanmon_cfgs = create_chanmon_cfgs(2);
5517         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5518         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5519         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5520
5521         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5522
5523         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5524         let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5525
5526         mine_transaction(&nodes[0], &closing_tx);
5527         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
5528         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5529
5530         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5531         assert_eq!(spend_txn.len(), 1);
5532         check_spends!(spend_txn[0], closing_tx);
5533
5534         mine_transaction(&nodes[1], &closing_tx);
5535         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[0].node.get_our_node_id()], 100000);
5536         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5537
5538         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5539         assert_eq!(spend_txn.len(), 1);
5540         check_spends!(spend_txn[0], closing_tx);
5541 }
5542
5543 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5544         let chanmon_cfgs = create_chanmon_cfgs(2);
5545         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5546         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5547         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5548         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5549
5550         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3_000_000 });
5551
5552         // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5553         // present in B's local commitment transaction, but none of A's commitment transactions.
5554         nodes[1].node.claim_funds(payment_preimage);
5555         check_added_monitors!(nodes[1], 1);
5556         expect_payment_claimed!(nodes[1], payment_hash, if use_dust { 50000 } else { 3_000_000 });
5557
5558         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5559         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5560         expect_payment_sent(&nodes[0], payment_preimage, None, false, false);
5561
5562         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5563         check_added_monitors!(nodes[0], 1);
5564         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5565         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5566         check_added_monitors!(nodes[1], 1);
5567
5568         let starting_block = nodes[1].best_block_info();
5569         let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5570         for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5571                 connect_block(&nodes[1], &block);
5572                 block.header.prev_blockhash = block.block_hash();
5573         }
5574         test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5575         check_closed_broadcast!(nodes[1], true);
5576         check_added_monitors!(nodes[1], 1);
5577         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
5578 }
5579
5580 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5581         let chanmon_cfgs = create_chanmon_cfgs(2);
5582         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5583         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5584         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5585         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5586
5587         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5588         nodes[0].node.send_payment_with_route(&route, payment_hash,
5589                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
5590         check_added_monitors!(nodes[0], 1);
5591
5592         let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5593
5594         // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5595         // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5596         // to "time out" the HTLC.
5597
5598         let starting_block = nodes[1].best_block_info();
5599         let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5600
5601         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5602                 connect_block(&nodes[0], &block);
5603                 block.header.prev_blockhash = block.block_hash();
5604         }
5605         test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5606         check_closed_broadcast!(nodes[0], true);
5607         check_added_monitors!(nodes[0], 1);
5608         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
5609 }
5610
5611 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5612         let chanmon_cfgs = create_chanmon_cfgs(3);
5613         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5614         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5615         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5616         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5617
5618         // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5619         // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5620         // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5621         // actually revoked.
5622         let htlc_value = if use_dust { 50000 } else { 3000000 };
5623         let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5624         nodes[1].node.fail_htlc_backwards(&our_payment_hash);
5625         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
5626         check_added_monitors!(nodes[1], 1);
5627
5628         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5629         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5630         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5631         check_added_monitors!(nodes[0], 1);
5632         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5633         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5634         check_added_monitors!(nodes[1], 1);
5635         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5636         check_added_monitors!(nodes[1], 1);
5637         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5638
5639         if check_revoke_no_close {
5640                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5641                 check_added_monitors!(nodes[0], 1);
5642         }
5643
5644         let starting_block = nodes[1].best_block_info();
5645         let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5646         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5647                 connect_block(&nodes[0], &block);
5648                 block.header.prev_blockhash = block.block_hash();
5649         }
5650         if !check_revoke_no_close {
5651                 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5652                 check_closed_broadcast!(nodes[0], true);
5653                 check_added_monitors!(nodes[0], 1);
5654                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
5655         } else {
5656                 expect_payment_failed!(nodes[0], our_payment_hash, true);
5657         }
5658 }
5659
5660 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5661 // There are only a few cases to test here:
5662 //  * its not really normative behavior, but we test that below-dust HTLCs "included" in
5663 //    broadcastable commitment transactions result in channel closure,
5664 //  * its included in an unrevoked-but-previous remote commitment transaction,
5665 //  * its included in the latest remote or local commitment transactions.
5666 // We test each of the three possible commitment transactions individually and use both dust and
5667 // non-dust HTLCs.
5668 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5669 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5670 // tested for at least one of the cases in other tests.
5671 #[test]
5672 fn htlc_claim_single_commitment_only_a() {
5673         do_htlc_claim_local_commitment_only(true);
5674         do_htlc_claim_local_commitment_only(false);
5675
5676         do_htlc_claim_current_remote_commitment_only(true);
5677         do_htlc_claim_current_remote_commitment_only(false);
5678 }
5679
5680 #[test]
5681 fn htlc_claim_single_commitment_only_b() {
5682         do_htlc_claim_previous_remote_commitment_only(true, false);
5683         do_htlc_claim_previous_remote_commitment_only(false, false);
5684         do_htlc_claim_previous_remote_commitment_only(true, true);
5685         do_htlc_claim_previous_remote_commitment_only(false, true);
5686 }
5687
5688 #[test]
5689 #[should_panic]
5690 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5691         let chanmon_cfgs = create_chanmon_cfgs(2);
5692         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5693         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5694         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5695         // Force duplicate randomness for every get-random call
5696         for node in nodes.iter() {
5697                 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
5698         }
5699
5700         // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5701         let channel_value_satoshis=10000;
5702         let push_msat=10001;
5703         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5704         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5705         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5706         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
5707
5708         // Create a second channel with the same random values. This used to panic due to a colliding
5709         // channel_id, but now panics due to a colliding outbound SCID alias.
5710         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5711 }
5712
5713 #[test]
5714 fn bolt2_open_channel_sending_node_checks_part2() {
5715         let chanmon_cfgs = create_chanmon_cfgs(2);
5716         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5717         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5718         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5719
5720         // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5721         let channel_value_satoshis=2^24;
5722         let push_msat=10001;
5723         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5724
5725         // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5726         let channel_value_satoshis=10000;
5727         // Test when push_msat is equal to 1000 * funding_satoshis.
5728         let push_msat=1000*channel_value_satoshis+1;
5729         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5730
5731         // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5732         let channel_value_satoshis=10000;
5733         let push_msat=10001;
5734         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
5735         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5736         assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5737
5738         // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5739         // 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
5740         assert!(node0_to_1_send_open_channel.channel_flags<=1);
5741
5742         // 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.
5743         assert!(BREAKDOWN_TIMEOUT>0);
5744         assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5745
5746         // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5747         let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5748         assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5749
5750         // 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.
5751         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5752         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5753         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5754         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5755         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5756 }
5757
5758 #[test]
5759 fn bolt2_open_channel_sane_dust_limit() {
5760         let chanmon_cfgs = create_chanmon_cfgs(2);
5761         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5762         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5763         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5764
5765         let channel_value_satoshis=1000000;
5766         let push_msat=10001;
5767         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5768         let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5769         node0_to_1_send_open_channel.dust_limit_satoshis = 547;
5770         node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
5771
5772         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5773         let events = nodes[1].node.get_and_clear_pending_msg_events();
5774         let err_msg = match events[0] {
5775                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
5776                         msg.clone()
5777                 },
5778                 _ => panic!("Unexpected event"),
5779         };
5780         assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
5781 }
5782
5783 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5784 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5785 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5786 // is no longer affordable once it's freed.
5787 #[test]
5788 fn test_fail_holding_cell_htlc_upon_free() {
5789         let chanmon_cfgs = create_chanmon_cfgs(2);
5790         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5791         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5792         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5793         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5794
5795         // First nodes[0] generates an update_fee, setting the channel's
5796         // pending_update_fee.
5797         {
5798                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5799                 *feerate_lock += 20;
5800         }
5801         nodes[0].node.timer_tick_occurred();
5802         check_added_monitors!(nodes[0], 1);
5803
5804         let events = nodes[0].node.get_and_clear_pending_msg_events();
5805         assert_eq!(events.len(), 1);
5806         let (update_msg, commitment_signed) = match events[0] {
5807                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5808                         (update_fee.as_ref(), commitment_signed)
5809                 },
5810                 _ => panic!("Unexpected event"),
5811         };
5812
5813         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5814
5815         let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5816         let channel_reserve = chan_stat.channel_reserve_msat;
5817         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5818         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
5819
5820         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5821         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
5822         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
5823
5824         // Send a payment which passes reserve checks but gets stuck in the holding cell.
5825         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
5826                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5827         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5828         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5829
5830         // Flush the pending fee update.
5831         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5832         let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5833         check_added_monitors!(nodes[1], 1);
5834         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
5835         check_added_monitors!(nodes[0], 1);
5836
5837         // Upon receipt of the RAA, there will be an attempt to resend the holding cell
5838         // HTLC, but now that the fee has been raised the payment will now fail, causing
5839         // us to surface its failure to the user.
5840         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5841         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5842         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Freeing holding cell with 1 HTLC updates in channel {}", chan.2), 1);
5843
5844         // Check that the payment failed to be sent out.
5845         let events = nodes[0].node.get_and_clear_pending_events();
5846         assert_eq!(events.len(), 2);
5847         match &events[0] {
5848                 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
5849                         assert_eq!(PaymentId(our_payment_hash.0), *payment_id.as_ref().unwrap());
5850                         assert_eq!(our_payment_hash.clone(), *payment_hash);
5851                         assert_eq!(*payment_failed_permanently, false);
5852                         assert_eq!(*short_channel_id, Some(route.paths[0].hops[0].short_channel_id));
5853                 },
5854                 _ => panic!("Unexpected event"),
5855         }
5856         match &events[1] {
5857                 &Event::PaymentFailed { ref payment_hash, .. } => {
5858                         assert_eq!(our_payment_hash.clone(), *payment_hash);
5859                 },
5860                 _ => panic!("Unexpected event"),
5861         }
5862 }
5863
5864 // Test that if multiple HTLCs are released from the holding cell and one is
5865 // valid but the other is no longer valid upon release, the valid HTLC can be
5866 // successfully completed while the other one fails as expected.
5867 #[test]
5868 fn test_free_and_fail_holding_cell_htlcs() {
5869         let chanmon_cfgs = create_chanmon_cfgs(2);
5870         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5871         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5872         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5873         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5874
5875         // First nodes[0] generates an update_fee, setting the channel's
5876         // pending_update_fee.
5877         {
5878                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5879                 *feerate_lock += 200;
5880         }
5881         nodes[0].node.timer_tick_occurred();
5882         check_added_monitors!(nodes[0], 1);
5883
5884         let events = nodes[0].node.get_and_clear_pending_msg_events();
5885         assert_eq!(events.len(), 1);
5886         let (update_msg, commitment_signed) = match events[0] {
5887                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5888                         (update_fee.as_ref(), commitment_signed)
5889                 },
5890                 _ => panic!("Unexpected event"),
5891         };
5892
5893         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5894
5895         let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5896         let channel_reserve = chan_stat.channel_reserve_msat;
5897         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5898         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
5899
5900         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5901         let amt_1 = 20000;
5902         let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, &channel_type_features) - amt_1;
5903         let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
5904         let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
5905
5906         // Send 2 payments which pass reserve checks but get stuck in the holding cell.
5907         nodes[0].node.send_payment_with_route(&route_1, payment_hash_1,
5908                 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
5909         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5910         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
5911         let payment_id_2 = PaymentId(nodes[0].keys_manager.get_secure_random_bytes());
5912         nodes[0].node.send_payment_with_route(&route_2, payment_hash_2,
5913                 RecipientOnionFields::secret_only(payment_secret_2), payment_id_2).unwrap();
5914         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5915         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
5916
5917         // Flush the pending fee update.
5918         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5919         let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5920         check_added_monitors!(nodes[1], 1);
5921         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
5922         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
5923         check_added_monitors!(nodes[0], 2);
5924
5925         // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
5926         // but now that the fee has been raised the second payment will now fail, causing us
5927         // to surface its failure to the user. The first payment should succeed.
5928         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5929         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5930         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Freeing holding cell with 2 HTLC updates in channel {}", chan.2), 1);
5931
5932         // Check that the second payment failed to be sent out.
5933         let events = nodes[0].node.get_and_clear_pending_events();
5934         assert_eq!(events.len(), 2);
5935         match &events[0] {
5936                 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
5937                         assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
5938                         assert_eq!(payment_hash_2.clone(), *payment_hash);
5939                         assert_eq!(*payment_failed_permanently, false);
5940                         assert_eq!(*short_channel_id, Some(route_2.paths[0].hops[0].short_channel_id));
5941                 },
5942                 _ => panic!("Unexpected event"),
5943         }
5944         match &events[1] {
5945                 &Event::PaymentFailed { ref payment_hash, .. } => {
5946                         assert_eq!(payment_hash_2.clone(), *payment_hash);
5947                 },
5948                 _ => panic!("Unexpected event"),
5949         }
5950
5951         // Complete the first payment and the RAA from the fee update.
5952         let (payment_event, send_raa_event) = {
5953                 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
5954                 assert_eq!(msgs.len(), 2);
5955                 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
5956         };
5957         let raa = match send_raa_event {
5958                 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
5959                 _ => panic!("Unexpected event"),
5960         };
5961         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
5962         check_added_monitors!(nodes[1], 1);
5963         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5964         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5965         let events = nodes[1].node.get_and_clear_pending_events();
5966         assert_eq!(events.len(), 1);
5967         match events[0] {
5968                 Event::PendingHTLCsForwardable { .. } => {},
5969                 _ => panic!("Unexpected event"),
5970         }
5971         nodes[1].node.process_pending_htlc_forwards();
5972         let events = nodes[1].node.get_and_clear_pending_events();
5973         assert_eq!(events.len(), 1);
5974         match events[0] {
5975                 Event::PaymentClaimable { .. } => {},
5976                 _ => panic!("Unexpected event"),
5977         }
5978         nodes[1].node.claim_funds(payment_preimage_1);
5979         check_added_monitors!(nodes[1], 1);
5980         expect_payment_claimed!(nodes[1], payment_hash_1, amt_1);
5981
5982         let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5983         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
5984         commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
5985         expect_payment_sent!(nodes[0], payment_preimage_1);
5986 }
5987
5988 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
5989 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
5990 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
5991 // once it's freed.
5992 #[test]
5993 fn test_fail_holding_cell_htlc_upon_free_multihop() {
5994         let chanmon_cfgs = create_chanmon_cfgs(3);
5995         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5996         // Avoid having to include routing fees in calculations
5997         let mut config = test_default_channel_config();
5998         config.channel_config.forwarding_fee_base_msat = 0;
5999         config.channel_config.forwarding_fee_proportional_millionths = 0;
6000         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
6001         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6002         let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6003         let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
6004
6005         // First nodes[1] generates an update_fee, setting the channel's
6006         // pending_update_fee.
6007         {
6008                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
6009                 *feerate_lock += 20;
6010         }
6011         nodes[1].node.timer_tick_occurred();
6012         check_added_monitors!(nodes[1], 1);
6013
6014         let events = nodes[1].node.get_and_clear_pending_msg_events();
6015         assert_eq!(events.len(), 1);
6016         let (update_msg, commitment_signed) = match events[0] {
6017                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6018                         (update_fee.as_ref(), commitment_signed)
6019                 },
6020                 _ => panic!("Unexpected event"),
6021         };
6022
6023         nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6024
6025         let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan_0_1.2);
6026         let channel_reserve = chan_stat.channel_reserve_msat;
6027         let feerate = get_feerate!(nodes[0], nodes[1], chan_0_1.2);
6028         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan_0_1.2);
6029
6030         // Send a payment which passes reserve checks but gets stuck in the holding cell.
6031         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
6032         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
6033         let payment_event = {
6034                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6035                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6036                 check_added_monitors!(nodes[0], 1);
6037
6038                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6039                 assert_eq!(events.len(), 1);
6040
6041                 SendEvent::from_event(events.remove(0))
6042         };
6043         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6044         check_added_monitors!(nodes[1], 0);
6045         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6046         expect_pending_htlcs_forwardable!(nodes[1]);
6047
6048         chan_stat = get_channel_value_stat!(nodes[1], nodes[2], chan_1_2.2);
6049         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6050
6051         // Flush the pending fee update.
6052         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6053         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6054         check_added_monitors!(nodes[2], 1);
6055         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6056         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6057         check_added_monitors!(nodes[1], 2);
6058
6059         // A final RAA message is generated to finalize the fee update.
6060         let events = nodes[1].node.get_and_clear_pending_msg_events();
6061         assert_eq!(events.len(), 1);
6062
6063         let raa_msg = match &events[0] {
6064                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6065                         msg.clone()
6066                 },
6067                 _ => panic!("Unexpected event"),
6068         };
6069
6070         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6071         check_added_monitors!(nodes[2], 1);
6072         assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6073
6074         // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6075         let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6076         assert_eq!(process_htlc_forwards_event.len(), 2);
6077         match &process_htlc_forwards_event[0] {
6078                 &Event::PendingHTLCsForwardable { .. } => {},
6079                 _ => panic!("Unexpected event"),
6080         }
6081
6082         // In response, we call ChannelManager's process_pending_htlc_forwards
6083         nodes[1].node.process_pending_htlc_forwards();
6084         check_added_monitors!(nodes[1], 1);
6085
6086         // This causes the HTLC to be failed backwards.
6087         let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6088         assert_eq!(fail_event.len(), 1);
6089         let (fail_msg, commitment_signed) = match &fail_event[0] {
6090                 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6091                         assert_eq!(updates.update_add_htlcs.len(), 0);
6092                         assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6093                         assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6094                         assert_eq!(updates.update_fail_htlcs.len(), 1);
6095                         (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6096                 },
6097                 _ => panic!("Unexpected event"),
6098         };
6099
6100         // Pass the failure messages back to nodes[0].
6101         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6102         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6103
6104         // Complete the HTLC failure+removal process.
6105         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6106         check_added_monitors!(nodes[0], 1);
6107         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6108         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6109         check_added_monitors!(nodes[1], 2);
6110         let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6111         assert_eq!(final_raa_event.len(), 1);
6112         let raa = match &final_raa_event[0] {
6113                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6114                 _ => panic!("Unexpected event"),
6115         };
6116         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6117         expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6118         check_added_monitors!(nodes[0], 1);
6119 }
6120
6121 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6122 // 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.
6123 //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.
6124
6125 #[test]
6126 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6127         //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6128         let chanmon_cfgs = create_chanmon_cfgs(2);
6129         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6130         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6131         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6132         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6133
6134         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6135         route.paths[0].hops[0].fee_msat = 100;
6136
6137         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6138                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6139                 ), true, APIError::ChannelUnavailable { .. }, {});
6140         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6141 }
6142
6143 #[test]
6144 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6145         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6146         let chanmon_cfgs = create_chanmon_cfgs(2);
6147         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6148         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6149         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6150         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6151
6152         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6153         route.paths[0].hops[0].fee_msat = 0;
6154         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6155                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)),
6156                 true, APIError::ChannelUnavailable { ref err },
6157                 assert_eq!(err, "Cannot send 0-msat HTLC"));
6158
6159         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6160         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send 0-msat HTLC", 1);
6161 }
6162
6163 #[test]
6164 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6165         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6166         let chanmon_cfgs = create_chanmon_cfgs(2);
6167         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6168         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6169         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6170         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6171
6172         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6173         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6174                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6175         check_added_monitors!(nodes[0], 1);
6176         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6177         updates.update_add_htlcs[0].amount_msat = 0;
6178
6179         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6180         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6181         check_closed_broadcast!(nodes[1], true).unwrap();
6182         check_added_monitors!(nodes[1], 1);
6183         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() },
6184                 [nodes[0].node.get_our_node_id()], 100000);
6185 }
6186
6187 #[test]
6188 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6189         //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6190         //It is enforced when constructing a route.
6191         let chanmon_cfgs = create_chanmon_cfgs(2);
6192         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6193         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6194         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6195         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6196
6197         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 0)
6198                 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
6199         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000);
6200         route.paths[0].hops.last_mut().unwrap().cltv_expiry_delta = 500000001;
6201         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6202                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6203                 ), true, APIError::InvalidRoute { ref err },
6204                 assert_eq!(err, &"Channel CLTV overflowed?"));
6205 }
6206
6207 #[test]
6208 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6209         //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.
6210         //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6211         //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6212         let chanmon_cfgs = create_chanmon_cfgs(2);
6213         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6214         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6215         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6216         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6217         let max_accepted_htlcs = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6218                 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().context.counterparty_max_accepted_htlcs as u64;
6219
6220         // Fetch a route in advance as we will be unable to once we're unable to send.
6221         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6222         for i in 0..max_accepted_htlcs {
6223                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6224                 let payment_event = {
6225                         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6226                                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6227                         check_added_monitors!(nodes[0], 1);
6228
6229                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6230                         assert_eq!(events.len(), 1);
6231                         if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6232                                 assert_eq!(htlcs[0].htlc_id, i);
6233                         } else {
6234                                 assert!(false);
6235                         }
6236                         SendEvent::from_event(events.remove(0))
6237                 };
6238                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6239                 check_added_monitors!(nodes[1], 0);
6240                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6241
6242                 expect_pending_htlcs_forwardable!(nodes[1]);
6243                 expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6244         }
6245         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6246                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6247                 ), true, APIError::ChannelUnavailable { .. }, {});
6248
6249         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6250 }
6251
6252 #[test]
6253 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6254         //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.
6255         let chanmon_cfgs = create_chanmon_cfgs(2);
6256         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6257         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6258         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6259         let channel_value = 100000;
6260         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0);
6261         let max_in_flight = get_channel_value_stat!(nodes[0], nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat;
6262
6263         send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6264
6265         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6266         // Manually create a route over our max in flight (which our router normally automatically
6267         // limits us to.
6268         route.paths[0].hops[0].fee_msat =  max_in_flight + 1;
6269         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6270                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6271                 ), true, APIError::ChannelUnavailable { .. }, {});
6272         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6273
6274         send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6275 }
6276
6277 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6278 #[test]
6279 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6280         //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6281         let chanmon_cfgs = create_chanmon_cfgs(2);
6282         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6283         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6284         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6285         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6286         let htlc_minimum_msat: u64;
6287         {
6288                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
6289                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
6290                 let channel = chan_lock.channel_by_id.get(&chan.2).unwrap();
6291                 htlc_minimum_msat = channel.context.get_holder_htlc_minimum_msat();
6292         }
6293
6294         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6295         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6296                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6297         check_added_monitors!(nodes[0], 1);
6298         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6299         updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6300         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6301         assert!(nodes[1].node.list_channels().is_empty());
6302         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6303         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()));
6304         check_added_monitors!(nodes[1], 1);
6305         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6306 }
6307
6308 #[test]
6309 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6310         //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
6311         let chanmon_cfgs = create_chanmon_cfgs(2);
6312         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6313         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6314         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6315         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6316
6317         let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6318         let channel_reserve = chan_stat.channel_reserve_msat;
6319         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
6320         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
6321         // The 2* and +1 are for the fee spike reserve.
6322         let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
6323
6324         let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6325         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6326         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6327                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6328         check_added_monitors!(nodes[0], 1);
6329         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6330
6331         // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6332         // at this time channel-initiatee receivers are not required to enforce that senders
6333         // respect the fee_spike_reserve.
6334         updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6335         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6336
6337         assert!(nodes[1].node.list_channels().is_empty());
6338         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6339         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6340         check_added_monitors!(nodes[1], 1);
6341         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6342 }
6343
6344 #[test]
6345 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6346         //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6347         //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
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
6354         let send_amt = 3999999;
6355         let (mut route, our_payment_hash, _, our_payment_secret) =
6356                 get_route_and_payment_hash!(nodes[0], nodes[1], 1000);
6357         route.paths[0].hops[0].fee_msat = send_amt;
6358         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6359         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6360         let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6361         let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(
6362                 &route.paths[0], send_amt, RecipientOnionFields::secret_only(our_payment_secret), cur_height, &None).unwrap();
6363         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash).unwrap();
6364
6365         let mut msg = msgs::UpdateAddHTLC {
6366                 channel_id: chan.2,
6367                 htlc_id: 0,
6368                 amount_msat: 1000,
6369                 payment_hash: our_payment_hash,
6370                 cltv_expiry: htlc_cltv,
6371                 onion_routing_packet: onion_packet.clone(),
6372                 skimmed_fee_msat: None,
6373         };
6374
6375         for i in 0..50 {
6376                 msg.htlc_id = i as u64;
6377                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6378         }
6379         msg.htlc_id = (50) as u64;
6380         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6381
6382         assert!(nodes[1].node.list_channels().is_empty());
6383         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6384         assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6385         check_added_monitors!(nodes[1], 1);
6386         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6387 }
6388
6389 #[test]
6390 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6391         //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6392         let chanmon_cfgs = create_chanmon_cfgs(2);
6393         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6394         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6395         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6396         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6397
6398         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6399         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6400                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6401         check_added_monitors!(nodes[0], 1);
6402         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6403         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;
6404         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6405
6406         assert!(nodes[1].node.list_channels().is_empty());
6407         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6408         assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6409         check_added_monitors!(nodes[1], 1);
6410         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 1000000);
6411 }
6412
6413 #[test]
6414 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6415         //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6416         let chanmon_cfgs = create_chanmon_cfgs(2);
6417         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6418         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6419         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6420
6421         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6422         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6423         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6424                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6425         check_added_monitors!(nodes[0], 1);
6426         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6427         updates.update_add_htlcs[0].cltv_expiry = 500000000;
6428         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6429
6430         assert!(nodes[1].node.list_channels().is_empty());
6431         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6432         assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6433         check_added_monitors!(nodes[1], 1);
6434         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6435 }
6436
6437 #[test]
6438 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6439         //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6440         // We test this by first testing that that repeated HTLCs pass commitment signature checks
6441         // after disconnect and that non-sequential htlc_ids result in a channel failure.
6442         let chanmon_cfgs = create_chanmon_cfgs(2);
6443         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6444         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6445         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6446
6447         create_announced_chan_between_nodes(&nodes, 0, 1);
6448         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6449         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6450                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6451         check_added_monitors!(nodes[0], 1);
6452         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6453         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6454
6455         //Disconnect and Reconnect
6456         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
6457         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
6458         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
6459                 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
6460         }, true).unwrap();
6461         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6462         assert_eq!(reestablish_1.len(), 1);
6463         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
6464                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
6465         }, false).unwrap();
6466         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6467         assert_eq!(reestablish_2.len(), 1);
6468         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6469         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6470         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6471         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6472
6473         //Resend HTLC
6474         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6475         assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6476         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6477         check_added_monitors!(nodes[1], 1);
6478         let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6479
6480         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6481
6482         assert!(nodes[1].node.list_channels().is_empty());
6483         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6484         assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6485         check_added_monitors!(nodes[1], 1);
6486         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6487 }
6488
6489 #[test]
6490 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6491         //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.
6492
6493         let chanmon_cfgs = create_chanmon_cfgs(2);
6494         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6495         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6496         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6497         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6498         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6499         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6500                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6501
6502         check_added_monitors!(nodes[0], 1);
6503         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6504         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6505
6506         let update_msg = msgs::UpdateFulfillHTLC{
6507                 channel_id: chan.2,
6508                 htlc_id: 0,
6509                 payment_preimage: our_payment_preimage,
6510         };
6511
6512         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6513
6514         assert!(nodes[0].node.list_channels().is_empty());
6515         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6516         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()));
6517         check_added_monitors!(nodes[0], 1);
6518         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6519 }
6520
6521 #[test]
6522 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6523         //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.
6524
6525         let chanmon_cfgs = create_chanmon_cfgs(2);
6526         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6527         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6528         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6529         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6530
6531         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6532         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6533                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6534         check_added_monitors!(nodes[0], 1);
6535         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6536         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6537
6538         let update_msg = msgs::UpdateFailHTLC{
6539                 channel_id: chan.2,
6540                 htlc_id: 0,
6541                 reason: msgs::OnionErrorPacket { data: Vec::new()},
6542         };
6543
6544         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6545
6546         assert!(nodes[0].node.list_channels().is_empty());
6547         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6548         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()));
6549         check_added_monitors!(nodes[0], 1);
6550         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6551 }
6552
6553 #[test]
6554 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6555         //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.
6556
6557         let chanmon_cfgs = create_chanmon_cfgs(2);
6558         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6559         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6560         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6561         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6562
6563         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6564         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6565                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6566         check_added_monitors!(nodes[0], 1);
6567         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6568         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6569         let update_msg = msgs::UpdateFailMalformedHTLC{
6570                 channel_id: chan.2,
6571                 htlc_id: 0,
6572                 sha256_of_onion: [1; 32],
6573                 failure_code: 0x8000,
6574         };
6575
6576         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6577
6578         assert!(nodes[0].node.list_channels().is_empty());
6579         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6580         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()));
6581         check_added_monitors!(nodes[0], 1);
6582         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6583 }
6584
6585 #[test]
6586 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6587         //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6588
6589         let chanmon_cfgs = create_chanmon_cfgs(2);
6590         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6591         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6592         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6593         create_announced_chan_between_nodes(&nodes, 0, 1);
6594
6595         let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6596
6597         nodes[1].node.claim_funds(our_payment_preimage);
6598         check_added_monitors!(nodes[1], 1);
6599         expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6600
6601         let events = nodes[1].node.get_and_clear_pending_msg_events();
6602         assert_eq!(events.len(), 1);
6603         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6604                 match events[0] {
6605                         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, .. } } => {
6606                                 assert!(update_add_htlcs.is_empty());
6607                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6608                                 assert!(update_fail_htlcs.is_empty());
6609                                 assert!(update_fail_malformed_htlcs.is_empty());
6610                                 assert!(update_fee.is_none());
6611                                 update_fulfill_htlcs[0].clone()
6612                         },
6613                         _ => panic!("Unexpected event"),
6614                 }
6615         };
6616
6617         update_fulfill_msg.htlc_id = 1;
6618
6619         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6620
6621         assert!(nodes[0].node.list_channels().is_empty());
6622         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6623         assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6624         check_added_monitors!(nodes[0], 1);
6625         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6626 }
6627
6628 #[test]
6629 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6630         //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.
6631
6632         let chanmon_cfgs = create_chanmon_cfgs(2);
6633         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6634         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6635         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6636         create_announced_chan_between_nodes(&nodes, 0, 1);
6637
6638         let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6639
6640         nodes[1].node.claim_funds(our_payment_preimage);
6641         check_added_monitors!(nodes[1], 1);
6642         expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6643
6644         let events = nodes[1].node.get_and_clear_pending_msg_events();
6645         assert_eq!(events.len(), 1);
6646         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6647                 match events[0] {
6648                         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, .. } } => {
6649                                 assert!(update_add_htlcs.is_empty());
6650                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6651                                 assert!(update_fail_htlcs.is_empty());
6652                                 assert!(update_fail_malformed_htlcs.is_empty());
6653                                 assert!(update_fee.is_none());
6654                                 update_fulfill_htlcs[0].clone()
6655                         },
6656                         _ => panic!("Unexpected event"),
6657                 }
6658         };
6659
6660         update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6661
6662         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6663
6664         assert!(nodes[0].node.list_channels().is_empty());
6665         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6666         assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6667         check_added_monitors!(nodes[0], 1);
6668         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6669 }
6670
6671 #[test]
6672 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6673         //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.
6674
6675         let chanmon_cfgs = create_chanmon_cfgs(2);
6676         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6677         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6678         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6679         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6680
6681         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6682         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6683                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6684         check_added_monitors!(nodes[0], 1);
6685
6686         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6687         updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6688
6689         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6690         check_added_monitors!(nodes[1], 0);
6691         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6692
6693         let events = nodes[1].node.get_and_clear_pending_msg_events();
6694
6695         let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6696                 match events[0] {
6697                         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, .. } } => {
6698                                 assert!(update_add_htlcs.is_empty());
6699                                 assert!(update_fulfill_htlcs.is_empty());
6700                                 assert!(update_fail_htlcs.is_empty());
6701                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6702                                 assert!(update_fee.is_none());
6703                                 update_fail_malformed_htlcs[0].clone()
6704                         },
6705                         _ => panic!("Unexpected event"),
6706                 }
6707         };
6708         update_msg.failure_code &= !0x8000;
6709         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6710
6711         assert!(nodes[0].node.list_channels().is_empty());
6712         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6713         assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6714         check_added_monitors!(nodes[0], 1);
6715         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 1000000);
6716 }
6717
6718 #[test]
6719 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6720         //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6721         //    * 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.
6722
6723         let chanmon_cfgs = create_chanmon_cfgs(3);
6724         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6725         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6726         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6727         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6728         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000);
6729
6730         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
6731
6732         //First hop
6733         let mut payment_event = {
6734                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6735                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6736                 check_added_monitors!(nodes[0], 1);
6737                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6738                 assert_eq!(events.len(), 1);
6739                 SendEvent::from_event(events.remove(0))
6740         };
6741         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6742         check_added_monitors!(nodes[1], 0);
6743         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6744         expect_pending_htlcs_forwardable!(nodes[1]);
6745         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6746         assert_eq!(events_2.len(), 1);
6747         check_added_monitors!(nodes[1], 1);
6748         payment_event = SendEvent::from_event(events_2.remove(0));
6749         assert_eq!(payment_event.msgs.len(), 1);
6750
6751         //Second Hop
6752         payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6753         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6754         check_added_monitors!(nodes[2], 0);
6755         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6756
6757         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6758         assert_eq!(events_3.len(), 1);
6759         let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6760                 match events_3[0] {
6761                         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 } } => {
6762                                 assert!(update_add_htlcs.is_empty());
6763                                 assert!(update_fulfill_htlcs.is_empty());
6764                                 assert!(update_fail_htlcs.is_empty());
6765                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6766                                 assert!(update_fee.is_none());
6767                                 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6768                         },
6769                         _ => panic!("Unexpected event"),
6770                 }
6771         };
6772
6773         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6774
6775         check_added_monitors!(nodes[1], 0);
6776         commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6777         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 }]);
6778         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6779         assert_eq!(events_4.len(), 1);
6780
6781         //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6782         match events_4[0] {
6783                 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, .. } } => {
6784                         assert!(update_add_htlcs.is_empty());
6785                         assert!(update_fulfill_htlcs.is_empty());
6786                         assert_eq!(update_fail_htlcs.len(), 1);
6787                         assert!(update_fail_malformed_htlcs.is_empty());
6788                         assert!(update_fee.is_none());
6789                 },
6790                 _ => panic!("Unexpected event"),
6791         };
6792
6793         check_added_monitors!(nodes[1], 1);
6794 }
6795
6796 #[test]
6797 fn test_channel_failed_after_message_with_badonion_node_perm_bits_set() {
6798         let chanmon_cfgs = create_chanmon_cfgs(3);
6799         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6800         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6801         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6802         create_announced_chan_between_nodes(&nodes, 0, 1);
6803         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6804
6805         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100_000);
6806
6807         // First hop
6808         let mut payment_event = {
6809                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6810                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6811                 check_added_monitors!(nodes[0], 1);
6812                 SendEvent::from_node(&nodes[0])
6813         };
6814
6815         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6816         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6817         expect_pending_htlcs_forwardable!(nodes[1]);
6818         check_added_monitors!(nodes[1], 1);
6819         payment_event = SendEvent::from_node(&nodes[1]);
6820         assert_eq!(payment_event.msgs.len(), 1);
6821
6822         // Second Hop
6823         payment_event.msgs[0].onion_routing_packet.version = 1; // Trigger an invalid_onion_version error
6824         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6825         check_added_monitors!(nodes[2], 0);
6826         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6827
6828         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6829         assert_eq!(events_3.len(), 1);
6830         match events_3[0] {
6831                 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6832                         let mut update_msg = updates.update_fail_malformed_htlcs[0].clone();
6833                         // Set the NODE bit (BADONION and PERM already set in invalid_onion_version error)
6834                         update_msg.failure_code |= 0x2000;
6835
6836                         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg);
6837                         commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true);
6838                 },
6839                 _ => panic!("Unexpected event"),
6840         }
6841
6842         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
6843                 vec![HTLCDestination::NextHopChannel {
6844                         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         check_added_monitors!(nodes[1], 1);
6848
6849         match events_4[0] {
6850                 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6851                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
6852                         commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
6853                 },
6854                 _ => panic!("Unexpected event"),
6855         }
6856
6857         let events_5 = nodes[0].node.get_and_clear_pending_events();
6858         assert_eq!(events_5.len(), 2);
6859
6860         // Expect a PaymentPathFailed event with a ChannelFailure network update for the channel between
6861         // the node originating the error to its next hop.
6862         match events_5[0] {
6863                 Event::PaymentPathFailed { error_code, failure: PathFailure::OnPath { network_update: Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent }) }, ..
6864                 } => {
6865                         assert_eq!(short_channel_id, chan_2.0.contents.short_channel_id);
6866                         assert!(is_permanent);
6867                         assert_eq!(error_code, Some(0x8000|0x4000|0x2000|4));
6868                 },
6869                 _ => panic!("Unexpected event"),
6870         }
6871         match events_5[1] {
6872                 Event::PaymentFailed { payment_hash, .. } => {
6873                         assert_eq!(payment_hash, our_payment_hash);
6874                 },
6875                 _ => panic!("Unexpected event"),
6876         }
6877
6878         // TODO: Test actual removal of channel from NetworkGraph when it's implemented.
6879 }
6880
6881 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6882         // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6883         // 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
6884         // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6885
6886         let mut chanmon_cfgs = create_chanmon_cfgs(2);
6887         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
6888         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6889         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6890         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6891         let chan =create_announced_chan_between_nodes(&nodes, 0, 1);
6892
6893         let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6894                 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().context.holder_dust_limit_satoshis;
6895
6896         // We route 2 dust-HTLCs between A and B
6897         let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6898         let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6899         route_payment(&nodes[0], &[&nodes[1]], 1000000);
6900
6901         // Cache one local commitment tx as previous
6902         let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6903
6904         // Fail one HTLC to prune it in the will-be-latest-local commitment tx
6905         nodes[1].node.fail_htlc_backwards(&payment_hash_2);
6906         check_added_monitors!(nodes[1], 0);
6907         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
6908         check_added_monitors!(nodes[1], 1);
6909
6910         let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6911         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
6912         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
6913         check_added_monitors!(nodes[0], 1);
6914
6915         // Cache one local commitment tx as lastest
6916         let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6917
6918         let events = nodes[0].node.get_and_clear_pending_msg_events();
6919         match events[0] {
6920                 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
6921                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
6922                 },
6923                 _ => panic!("Unexpected event"),
6924         }
6925         match events[1] {
6926                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
6927                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
6928                 },
6929                 _ => panic!("Unexpected event"),
6930         }
6931
6932         assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
6933         // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
6934         if announce_latest {
6935                 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
6936         } else {
6937                 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
6938         }
6939
6940         check_closed_broadcast!(nodes[0], true);
6941         check_added_monitors!(nodes[0], 1);
6942         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
6943
6944         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6945         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6946         let events = nodes[0].node.get_and_clear_pending_events();
6947         // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
6948         assert_eq!(events.len(), 4);
6949         let mut first_failed = false;
6950         for event in events {
6951                 match event {
6952                         Event::PaymentPathFailed { payment_hash, .. } => {
6953                                 if payment_hash == payment_hash_1 {
6954                                         assert!(!first_failed);
6955                                         first_failed = true;
6956                                 } else {
6957                                         assert_eq!(payment_hash, payment_hash_2);
6958                                 }
6959                         },
6960                         Event::PaymentFailed { .. } => {}
6961                         _ => panic!("Unexpected event"),
6962                 }
6963         }
6964 }
6965
6966 #[test]
6967 fn test_failure_delay_dust_htlc_local_commitment() {
6968         do_test_failure_delay_dust_htlc_local_commitment(true);
6969         do_test_failure_delay_dust_htlc_local_commitment(false);
6970 }
6971
6972 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
6973         // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
6974         // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
6975         // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
6976         // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
6977         // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
6978         // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
6979
6980         let chanmon_cfgs = create_chanmon_cfgs(3);
6981         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6982         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6983         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6984         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6985
6986         let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6987                 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().context.holder_dust_limit_satoshis;
6988
6989         let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6990         let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6991
6992         let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6993         let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
6994
6995         // We revoked bs_commitment_tx
6996         if revoked {
6997                 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6998                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
6999         }
7000
7001         let mut timeout_tx = Vec::new();
7002         if local {
7003                 // We fail dust-HTLC 1 by broadcast of local commitment tx
7004                 mine_transaction(&nodes[0], &as_commitment_tx[0]);
7005                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
7006                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7007                 expect_payment_failed!(nodes[0], dust_hash, false);
7008
7009                 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
7010                 check_closed_broadcast!(nodes[0], true);
7011                 check_added_monitors!(nodes[0], 1);
7012                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7013                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
7014                 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7015                 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7016                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7017                 mine_transaction(&nodes[0], &timeout_tx[0]);
7018                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7019                 expect_payment_failed!(nodes[0], non_dust_hash, false);
7020         } else {
7021                 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7022                 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
7023                 check_closed_broadcast!(nodes[0], true);
7024                 check_added_monitors!(nodes[0], 1);
7025                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
7026                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7027
7028                 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
7029                 timeout_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().drain(..)
7030                         .filter(|tx| tx.input[0].previous_output.txid == bs_commitment_tx[0].txid()).collect();
7031                 check_spends!(timeout_tx[0], bs_commitment_tx[0]);
7032                 // For both a revoked or non-revoked commitment transaction, after ANTI_REORG_DELAY the
7033                 // dust HTLC should have been failed.
7034                 expect_payment_failed!(nodes[0], dust_hash, false);
7035
7036                 if !revoked {
7037                         assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7038                 } else {
7039                         assert_eq!(timeout_tx[0].lock_time.0, 11);
7040                 }
7041                 // We fail non-dust-HTLC 2 by broadcast of local timeout/revocation-claim tx
7042                 mine_transaction(&nodes[0], &timeout_tx[0]);
7043                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7044                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7045                 expect_payment_failed!(nodes[0], non_dust_hash, false);
7046         }
7047 }
7048
7049 #[test]
7050 fn test_sweep_outbound_htlc_failure_update() {
7051         do_test_sweep_outbound_htlc_failure_update(false, true);
7052         do_test_sweep_outbound_htlc_failure_update(false, false);
7053         do_test_sweep_outbound_htlc_failure_update(true, false);
7054 }
7055
7056 #[test]
7057 fn test_user_configurable_csv_delay() {
7058         // We test our channel constructors yield errors when we pass them absurd csv delay
7059
7060         let mut low_our_to_self_config = UserConfig::default();
7061         low_our_to_self_config.channel_handshake_config.our_to_self_delay = 6;
7062         let mut high_their_to_self_config = UserConfig::default();
7063         high_their_to_self_config.channel_handshake_limits.their_to_self_delay = 100;
7064         let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7065         let chanmon_cfgs = create_chanmon_cfgs(2);
7066         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7067         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7068         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7069
7070         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in OutboundV1Channel::new()
7071         if let Err(error) = OutboundV1Channel::new(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7072                 &nodes[0].keys_manager, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &nodes[1].node.init_features(), 1000000, 1000000, 0,
7073                 &low_our_to_self_config, 0, 42)
7074         {
7075                 match error {
7076                         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())); },
7077                         _ => panic!("Unexpected event"),
7078                 }
7079         } else { assert!(false) }
7080
7081         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in InboundV1Channel::new()
7082         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7083         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7084         open_channel.to_self_delay = 200;
7085         if let Err(error) = InboundV1Channel::new(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7086                 &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,
7087                 &low_our_to_self_config, 0, &nodes[0].logger, /*is_0conf=*/false)
7088         {
7089                 match error {
7090                         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()));  },
7091                         _ => panic!("Unexpected event"),
7092                 }
7093         } else { assert!(false); }
7094
7095         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7096         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7097         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()));
7098         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7099         accept_channel.to_self_delay = 200;
7100         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
7101         let reason_msg;
7102         if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7103                 match action {
7104                         &ErrorAction::SendErrorMessage { ref msg } => {
7105                                 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()));
7106                                 reason_msg = msg.data.clone();
7107                         },
7108                         _ => { panic!(); }
7109                 }
7110         } else { panic!(); }
7111         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg }, [nodes[1].node.get_our_node_id()], 1000000);
7112
7113         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in InboundV1Channel::new()
7114         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7115         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7116         open_channel.to_self_delay = 200;
7117         if let Err(error) = InboundV1Channel::new(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7118                 &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,
7119                 &high_their_to_self_config, 0, &nodes[0].logger, /*is_0conf=*/false)
7120         {
7121                 match error {
7122                         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())); },
7123                         _ => panic!("Unexpected event"),
7124                 }
7125         } else { assert!(false); }
7126 }
7127
7128 #[test]
7129 fn test_check_htlc_underpaying() {
7130         // Send payment through A -> B but A is maliciously
7131         // sending a probe payment (i.e less than expected value0
7132         // to B, B should refuse payment.
7133
7134         let chanmon_cfgs = create_chanmon_cfgs(2);
7135         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7136         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7137         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7138
7139         // Create some initial channels
7140         create_announced_chan_between_nodes(&nodes, 0, 1);
7141
7142         let scorer = test_utils::TestScorer::new();
7143         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7144         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(),
7145                 TEST_FINAL_CLTV).with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
7146         let route_params = RouteParameters::from_payment_params_and_value(payment_params, 10_000);
7147         let route = get_route(&nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph.read_only(),
7148                 None, nodes[0].logger, &scorer, &(), &random_seed_bytes).unwrap();
7149         let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7150         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200, None).unwrap();
7151         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
7152                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
7153         check_added_monitors!(nodes[0], 1);
7154
7155         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7156         assert_eq!(events.len(), 1);
7157         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7158         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7159         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7160
7161         // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7162         // and then will wait a second random delay before failing the HTLC back:
7163         expect_pending_htlcs_forwardable!(nodes[1]);
7164         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
7165
7166         // Node 3 is expecting payment of 100_000 but received 10_000,
7167         // it should fail htlc like we didn't know the preimage.
7168         nodes[1].node.process_pending_htlc_forwards();
7169
7170         let events = nodes[1].node.get_and_clear_pending_msg_events();
7171         assert_eq!(events.len(), 1);
7172         let (update_fail_htlc, commitment_signed) = match events[0] {
7173                 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 } } => {
7174                         assert!(update_add_htlcs.is_empty());
7175                         assert!(update_fulfill_htlcs.is_empty());
7176                         assert_eq!(update_fail_htlcs.len(), 1);
7177                         assert!(update_fail_malformed_htlcs.is_empty());
7178                         assert!(update_fee.is_none());
7179                         (update_fail_htlcs[0].clone(), commitment_signed)
7180                 },
7181                 _ => panic!("Unexpected event"),
7182         };
7183         check_added_monitors!(nodes[1], 1);
7184
7185         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7186         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7187
7188         // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7189         let mut expected_failure_data = (10_000 as u64).to_be_bytes().to_vec();
7190         expected_failure_data.extend_from_slice(&CHAN_CONFIRM_DEPTH.to_be_bytes());
7191         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7192 }
7193
7194 #[test]
7195 fn test_announce_disable_channels() {
7196         // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7197         // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7198
7199         let chanmon_cfgs = create_chanmon_cfgs(2);
7200         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7201         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7202         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7203
7204         create_announced_chan_between_nodes(&nodes, 0, 1);
7205         create_announced_chan_between_nodes(&nodes, 1, 0);
7206         create_announced_chan_between_nodes(&nodes, 0, 1);
7207
7208         // Disconnect peers
7209         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
7210         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
7211
7212         for _ in 0..DISABLE_GOSSIP_TICKS + 1 {
7213                 nodes[0].node.timer_tick_occurred();
7214         }
7215         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7216         assert_eq!(msg_events.len(), 3);
7217         let mut chans_disabled = HashMap::new();
7218         for e in msg_events {
7219                 match e {
7220                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7221                                 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7222                                 // Check that each channel gets updated exactly once
7223                                 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7224                                         panic!("Generated ChannelUpdate for wrong chan!");
7225                                 }
7226                         },
7227                         _ => panic!("Unexpected event"),
7228                 }
7229         }
7230         // Reconnect peers
7231         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
7232                 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
7233         }, true).unwrap();
7234         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7235         assert_eq!(reestablish_1.len(), 3);
7236         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
7237                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
7238         }, false).unwrap();
7239         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7240         assert_eq!(reestablish_2.len(), 3);
7241
7242         // Reestablish chan_1
7243         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7244         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7245         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7246         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7247         // Reestablish chan_2
7248         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7249         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7250         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7251         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7252         // Reestablish chan_3
7253         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7254         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7255         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7256         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7257
7258         for _ in 0..ENABLE_GOSSIP_TICKS {
7259                 nodes[0].node.timer_tick_occurred();
7260         }
7261         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7262         nodes[0].node.timer_tick_occurred();
7263         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7264         assert_eq!(msg_events.len(), 3);
7265         for e in msg_events {
7266                 match e {
7267                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7268                                 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7269                                 match chans_disabled.remove(&msg.contents.short_channel_id) {
7270                                         // Each update should have a higher timestamp than the previous one, replacing
7271                                         // the old one.
7272                                         Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7273                                         None => panic!("Generated ChannelUpdate for wrong chan!"),
7274                                 }
7275                         },
7276                         _ => panic!("Unexpected event"),
7277                 }
7278         }
7279         // Check that each channel gets updated exactly once
7280         assert!(chans_disabled.is_empty());
7281 }
7282
7283 #[test]
7284 fn test_bump_penalty_txn_on_revoked_commitment() {
7285         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7286         // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7287
7288         let chanmon_cfgs = create_chanmon_cfgs(2);
7289         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7290         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7291         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7292
7293         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7294
7295         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7296         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 30)
7297                 .with_bolt11_features(nodes[0].node.invoice_features()).unwrap();
7298         let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000);
7299         send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7300
7301         let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7302         // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7303         assert_eq!(revoked_txn[0].output.len(), 4);
7304         assert_eq!(revoked_txn[0].input.len(), 1);
7305         assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7306         let revoked_txid = revoked_txn[0].txid();
7307
7308         let mut penalty_sum = 0;
7309         for outp in revoked_txn[0].output.iter() {
7310                 if outp.script_pubkey.is_v0_p2wsh() {
7311                         penalty_sum += outp.value;
7312                 }
7313         }
7314
7315         // Connect blocks to change height_timer range to see if we use right soonest_timelock
7316         let header_114 = connect_blocks(&nodes[1], 14);
7317
7318         // Actually revoke tx by claiming a HTLC
7319         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7320         connect_block(&nodes[1], &create_dummy_block(header_114, 42, vec![revoked_txn[0].clone()]));
7321         check_added_monitors!(nodes[1], 1);
7322
7323         // One or more justice tx should have been broadcast, check it
7324         let penalty_1;
7325         let feerate_1;
7326         {
7327                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7328                 assert_eq!(node_txn.len(), 1); // justice tx (broadcasted from ChannelMonitor)
7329                 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7330                 assert_eq!(node_txn[0].output.len(), 1);
7331                 check_spends!(node_txn[0], revoked_txn[0]);
7332                 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7333                 feerate_1 = fee_1 * 1000 / node_txn[0].weight() as u64;
7334                 penalty_1 = node_txn[0].txid();
7335                 node_txn.clear();
7336         };
7337
7338         // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7339         connect_blocks(&nodes[1], 15);
7340         let mut penalty_2 = penalty_1;
7341         let mut feerate_2 = 0;
7342         {
7343                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7344                 assert_eq!(node_txn.len(), 1);
7345                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7346                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7347                         assert_eq!(node_txn[0].output.len(), 1);
7348                         check_spends!(node_txn[0], revoked_txn[0]);
7349                         penalty_2 = node_txn[0].txid();
7350                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7351                         assert_ne!(penalty_2, penalty_1);
7352                         let fee_2 = penalty_sum - node_txn[0].output[0].value;
7353                         feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7354                         // Verify 25% bump heuristic
7355                         assert!(feerate_2 * 100 >= feerate_1 * 125);
7356                         node_txn.clear();
7357                 }
7358         }
7359         assert_ne!(feerate_2, 0);
7360
7361         // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7362         connect_blocks(&nodes[1], 1);
7363         let penalty_3;
7364         let mut feerate_3 = 0;
7365         {
7366                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7367                 assert_eq!(node_txn.len(), 1);
7368                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7369                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7370                         assert_eq!(node_txn[0].output.len(), 1);
7371                         check_spends!(node_txn[0], revoked_txn[0]);
7372                         penalty_3 = node_txn[0].txid();
7373                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7374                         assert_ne!(penalty_3, penalty_2);
7375                         let fee_3 = penalty_sum - node_txn[0].output[0].value;
7376                         feerate_3 = fee_3 * 1000 / node_txn[0].weight() as u64;
7377                         // Verify 25% bump heuristic
7378                         assert!(feerate_3 * 100 >= feerate_2 * 125);
7379                         node_txn.clear();
7380                 }
7381         }
7382         assert_ne!(feerate_3, 0);
7383
7384         nodes[1].node.get_and_clear_pending_events();
7385         nodes[1].node.get_and_clear_pending_msg_events();
7386 }
7387
7388 #[test]
7389 fn test_bump_penalty_txn_on_revoked_htlcs() {
7390         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7391         // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7392
7393         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7394         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7395         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7396         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7397         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7398
7399         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7400         // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7401         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 50).with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
7402         let scorer = test_utils::TestScorer::new();
7403         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7404         let route_params = RouteParameters::from_payment_params_and_value(payment_params, 3_000_000);
7405         let route = get_route(&nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph.read_only(), None,
7406                 nodes[0].logger, &scorer, &(), &random_seed_bytes).unwrap();
7407         let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7408         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 50).with_bolt11_features(nodes[0].node.invoice_features()).unwrap();
7409         let route_params = RouteParameters::from_payment_params_and_value(payment_params, 3_000_000);
7410         let route = get_route(&nodes[1].node.get_our_node_id(), &route_params, &nodes[1].network_graph.read_only(), None,
7411                 nodes[0].logger, &scorer, &(), &random_seed_bytes).unwrap();
7412         send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7413
7414         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7415         assert_eq!(revoked_local_txn[0].input.len(), 1);
7416         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7417
7418         // Revoke local commitment tx
7419         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7420
7421         // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7422         connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![revoked_local_txn[0].clone()]));
7423         check_closed_broadcast!(nodes[1], true);
7424         check_added_monitors!(nodes[1], 1);
7425         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 1000000);
7426         connect_blocks(&nodes[1], 50); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7427
7428         let revoked_htlc_txn = {
7429                 let txn = nodes[1].tx_broadcaster.unique_txn_broadcast();
7430                 assert_eq!(txn.len(), 2);
7431
7432                 assert_eq!(txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7433                 assert_eq!(txn[0].input.len(), 1);
7434                 check_spends!(txn[0], revoked_local_txn[0]);
7435
7436                 assert_eq!(txn[1].input.len(), 1);
7437                 assert_eq!(txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7438                 assert_eq!(txn[1].output.len(), 1);
7439                 check_spends!(txn[1], revoked_local_txn[0]);
7440
7441                 txn
7442         };
7443
7444         // Broadcast set of revoked txn on A
7445         let hash_128 = connect_blocks(&nodes[0], 40);
7446         let block_11 = create_dummy_block(hash_128, 42, vec![revoked_local_txn[0].clone()]);
7447         connect_block(&nodes[0], &block_11);
7448         let block_129 = create_dummy_block(block_11.block_hash(), 42, vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()]);
7449         connect_block(&nodes[0], &block_129);
7450         let events = nodes[0].node.get_and_clear_pending_events();
7451         expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7452         match events.last().unwrap() {
7453                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7454                 _ => panic!("Unexpected event"),
7455         }
7456         let first;
7457         let feerate_1;
7458         let penalty_txn;
7459         {
7460                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7461                 assert_eq!(node_txn.len(), 4); // 3 penalty txn on revoked commitment tx + 1 penalty tnx on revoked HTLC txn
7462                 // Verify claim tx are spending revoked HTLC txn
7463
7464                 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7465                 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7466                 // which are included in the same block (they are broadcasted because we scan the
7467                 // transactions linearly and generate claims as we go, they likely should be removed in the
7468                 // future).
7469                 assert_eq!(node_txn[0].input.len(), 1);
7470                 check_spends!(node_txn[0], revoked_local_txn[0]);
7471                 assert_eq!(node_txn[1].input.len(), 1);
7472                 check_spends!(node_txn[1], revoked_local_txn[0]);
7473                 assert_eq!(node_txn[2].input.len(), 1);
7474                 check_spends!(node_txn[2], revoked_local_txn[0]);
7475
7476                 // Each of the three justice transactions claim a separate (single) output of the three
7477                 // available, which we check here:
7478                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7479                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7480                 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7481
7482                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7483                 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7484
7485                 // node_txn[3] spends the revoked outputs from the revoked_htlc_txn (which only have one
7486                 // output, checked above).
7487                 assert_eq!(node_txn[3].input.len(), 2);
7488                 assert_eq!(node_txn[3].output.len(), 1);
7489                 check_spends!(node_txn[3], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7490
7491                 first = node_txn[3].txid();
7492                 // Store both feerates for later comparison
7493                 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[3].output[0].value;
7494                 feerate_1 = fee_1 * 1000 / node_txn[3].weight() as u64;
7495                 penalty_txn = vec![node_txn[2].clone()];
7496                 node_txn.clear();
7497         }
7498
7499         // Connect one more block to see if bumped penalty are issued for HTLC txn
7500         let block_130 = create_dummy_block(block_129.block_hash(), 42, penalty_txn);
7501         connect_block(&nodes[0], &block_130);
7502         let block_131 = create_dummy_block(block_130.block_hash(), 42, Vec::new());
7503         connect_block(&nodes[0], &block_131);
7504
7505         // Few more blocks to confirm penalty txn
7506         connect_blocks(&nodes[0], 4);
7507         assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7508         let header_144 = connect_blocks(&nodes[0], 9);
7509         let node_txn = {
7510                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7511                 assert_eq!(node_txn.len(), 1);
7512
7513                 assert_eq!(node_txn[0].input.len(), 2);
7514                 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7515                 // Verify bumped tx is different and 25% bump heuristic
7516                 assert_ne!(first, node_txn[0].txid());
7517                 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7518                 let feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7519                 assert!(feerate_2 * 100 > feerate_1 * 125);
7520                 let txn = vec![node_txn[0].clone()];
7521                 node_txn.clear();
7522                 txn
7523         };
7524         // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7525         connect_block(&nodes[0], &create_dummy_block(header_144, 42, node_txn));
7526         connect_blocks(&nodes[0], 20);
7527         {
7528                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7529                 // We verify than no new transaction has been broadcast because previously
7530                 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7531                 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7532                 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7533                 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7534                 // up bumped justice generation.
7535                 assert_eq!(node_txn.len(), 0);
7536                 node_txn.clear();
7537         }
7538         check_closed_broadcast!(nodes[0], true);
7539         check_added_monitors!(nodes[0], 1);
7540 }
7541
7542 #[test]
7543 fn test_bump_penalty_txn_on_remote_commitment() {
7544         // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7545         // we're able to claim outputs on remote commitment transaction before timelocks expiration
7546
7547         // Create 2 HTLCs
7548         // Provide preimage for one
7549         // Check aggregation
7550
7551         let chanmon_cfgs = create_chanmon_cfgs(2);
7552         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7553         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7554         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7555
7556         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7557         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
7558         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7559
7560         // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7561         let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7562         assert_eq!(remote_txn[0].output.len(), 4);
7563         assert_eq!(remote_txn[0].input.len(), 1);
7564         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7565
7566         // Claim a HTLC without revocation (provide B monitor with preimage)
7567         nodes[1].node.claim_funds(payment_preimage);
7568         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
7569         mine_transaction(&nodes[1], &remote_txn[0]);
7570         check_added_monitors!(nodes[1], 2);
7571         connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
7572
7573         // One or more claim tx should have been broadcast, check it
7574         let timeout;
7575         let preimage;
7576         let preimage_bump;
7577         let feerate_timeout;
7578         let feerate_preimage;
7579         {
7580                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7581                 // 3 transactions including:
7582                 //   preimage and timeout sweeps from remote commitment + preimage sweep bump
7583                 assert_eq!(node_txn.len(), 3);
7584                 assert_eq!(node_txn[0].input.len(), 1);
7585                 assert_eq!(node_txn[1].input.len(), 1);
7586                 assert_eq!(node_txn[2].input.len(), 1);
7587                 check_spends!(node_txn[0], remote_txn[0]);
7588                 check_spends!(node_txn[1], remote_txn[0]);
7589                 check_spends!(node_txn[2], remote_txn[0]);
7590
7591                 preimage = node_txn[0].txid();
7592                 let index = node_txn[0].input[0].previous_output.vout;
7593                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7594                 feerate_preimage = fee * 1000 / node_txn[0].weight() as u64;
7595
7596                 let (preimage_bump_tx, timeout_tx) = if node_txn[2].input[0].previous_output == node_txn[0].input[0].previous_output {
7597                         (node_txn[2].clone(), node_txn[1].clone())
7598                 } else {
7599                         (node_txn[1].clone(), node_txn[2].clone())
7600                 };
7601
7602                 preimage_bump = preimage_bump_tx;
7603                 check_spends!(preimage_bump, remote_txn[0]);
7604                 assert_eq!(node_txn[0].input[0].previous_output, preimage_bump.input[0].previous_output);
7605
7606                 timeout = timeout_tx.txid();
7607                 let index = timeout_tx.input[0].previous_output.vout;
7608                 let fee = remote_txn[0].output[index as usize].value - timeout_tx.output[0].value;
7609                 feerate_timeout = fee * 1000 / timeout_tx.weight() as u64;
7610
7611                 node_txn.clear();
7612         };
7613         assert_ne!(feerate_timeout, 0);
7614         assert_ne!(feerate_preimage, 0);
7615
7616         // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7617         connect_blocks(&nodes[1], 1);
7618         {
7619                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7620                 assert_eq!(node_txn.len(), 1);
7621                 assert_eq!(node_txn[0].input.len(), 1);
7622                 assert_eq!(preimage_bump.input.len(), 1);
7623                 check_spends!(node_txn[0], remote_txn[0]);
7624                 check_spends!(preimage_bump, remote_txn[0]);
7625
7626                 let index = preimage_bump.input[0].previous_output.vout;
7627                 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
7628                 let new_feerate = fee * 1000 / preimage_bump.weight() as u64;
7629                 assert!(new_feerate * 100 > feerate_timeout * 125);
7630                 assert_ne!(timeout, preimage_bump.txid());
7631
7632                 let index = node_txn[0].input[0].previous_output.vout;
7633                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7634                 let new_feerate = fee * 1000 / node_txn[0].weight() as u64;
7635                 assert!(new_feerate * 100 > feerate_preimage * 125);
7636                 assert_ne!(preimage, node_txn[0].txid());
7637
7638                 node_txn.clear();
7639         }
7640
7641         nodes[1].node.get_and_clear_pending_events();
7642         nodes[1].node.get_and_clear_pending_msg_events();
7643 }
7644
7645 #[test]
7646 fn test_counterparty_raa_skip_no_crash() {
7647         // Previously, if our counterparty sent two RAAs in a row without us having provided a
7648         // commitment transaction, we would have happily carried on and provided them the next
7649         // commitment transaction based on one RAA forward. This would probably eventually have led to
7650         // channel closure, but it would not have resulted in funds loss. Still, our
7651         // TestChannelSigner would have panicked as it doesn't like jumps into the future. Here, we
7652         // check simply that the channel is closed in response to such an RAA, but don't check whether
7653         // we decide to punish our counterparty for revoking their funds (as we don't currently
7654         // implement that).
7655         let chanmon_cfgs = create_chanmon_cfgs(2);
7656         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7657         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7658         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7659         let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
7660
7661         let per_commitment_secret;
7662         let next_per_commitment_point;
7663         {
7664                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
7665                 let mut guard = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
7666                 let keys = guard.channel_by_id.get_mut(&channel_id).unwrap().get_signer();
7667
7668                 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7669
7670                 // Make signer believe we got a counterparty signature, so that it allows the revocation
7671                 keys.as_ecdsa().unwrap().get_enforcement_state().last_holder_commitment -= 1;
7672                 per_commitment_secret = keys.as_ref().release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
7673
7674                 // Must revoke without gaps
7675                 keys.as_ecdsa().unwrap().get_enforcement_state().last_holder_commitment -= 1;
7676                 keys.as_ref().release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
7677
7678                 keys.as_ecdsa().unwrap().get_enforcement_state().last_holder_commitment -= 1;
7679                 next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7680                         &SecretKey::from_slice(&keys.as_ref().release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7681         }
7682
7683         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7684                 &msgs::RevokeAndACK {
7685                         channel_id,
7686                         per_commitment_secret,
7687                         next_per_commitment_point,
7688                         #[cfg(taproot)]
7689                         next_local_nonce: None,
7690                 });
7691         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7692         check_added_monitors!(nodes[1], 1);
7693         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() }
7694                 , [nodes[0].node.get_our_node_id()], 100000);
7695 }
7696
7697 #[test]
7698 fn test_bump_txn_sanitize_tracking_maps() {
7699         // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7700         // verify we clean then right after expiration of ANTI_REORG_DELAY.
7701
7702         let chanmon_cfgs = create_chanmon_cfgs(2);
7703         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7704         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7705         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7706
7707         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7708         // Lock HTLC in both directions
7709         let (payment_preimage_1, _, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000);
7710         let (_, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000);
7711
7712         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7713         assert_eq!(revoked_local_txn[0].input.len(), 1);
7714         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7715
7716         // Revoke local commitment tx
7717         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
7718
7719         // Broadcast set of revoked txn on A
7720         connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
7721         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[0], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
7722         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
7723
7724         mine_transaction(&nodes[0], &revoked_local_txn[0]);
7725         check_closed_broadcast!(nodes[0], true);
7726         check_added_monitors!(nodes[0], 1);
7727         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 1000000);
7728         let penalty_txn = {
7729                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7730                 assert_eq!(node_txn.len(), 3); //ChannelMonitor: justice txn * 3
7731                 check_spends!(node_txn[0], revoked_local_txn[0]);
7732                 check_spends!(node_txn[1], revoked_local_txn[0]);
7733                 check_spends!(node_txn[2], revoked_local_txn[0]);
7734                 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7735                 node_txn.clear();
7736                 penalty_txn
7737         };
7738         connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, penalty_txn));
7739         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7740         {
7741                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
7742                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
7743                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
7744         }
7745 }
7746
7747 #[test]
7748 fn test_channel_conf_timeout() {
7749         // Tests that, for inbound channels, we give up on them if the funding transaction does not
7750         // confirm within 2016 blocks, as recommended by BOLT 2.
7751         let chanmon_cfgs = create_chanmon_cfgs(2);
7752         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7753         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7754         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7755
7756         let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000);
7757
7758         // The outbound node should wait forever for confirmation:
7759         // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
7760         // copied here instead of directly referencing the constant.
7761         connect_blocks(&nodes[0], 2016);
7762         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7763
7764         // The inbound node should fail the channel after exactly 2016 blocks
7765         connect_blocks(&nodes[1], 2015);
7766         check_added_monitors!(nodes[1], 0);
7767         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7768
7769         connect_blocks(&nodes[1], 1);
7770         check_added_monitors!(nodes[1], 1);
7771         check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut, [nodes[0].node.get_our_node_id()], 1000000);
7772         let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
7773         assert_eq!(close_ev.len(), 1);
7774         match close_ev[0] {
7775                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
7776                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7777                         assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
7778                 },
7779                 _ => panic!("Unexpected event"),
7780         }
7781 }
7782
7783 #[test]
7784 fn test_override_channel_config() {
7785         let chanmon_cfgs = create_chanmon_cfgs(2);
7786         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7787         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7788         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7789
7790         // Node0 initiates a channel to node1 using the override config.
7791         let mut override_config = UserConfig::default();
7792         override_config.channel_handshake_config.our_to_self_delay = 200;
7793
7794         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
7795
7796         // Assert the channel created by node0 is using the override config.
7797         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7798         assert_eq!(res.channel_flags, 0);
7799         assert_eq!(res.to_self_delay, 200);
7800 }
7801
7802 #[test]
7803 fn test_override_0msat_htlc_minimum() {
7804         let mut zero_config = UserConfig::default();
7805         zero_config.channel_handshake_config.our_htlc_minimum_msat = 0;
7806         let chanmon_cfgs = create_chanmon_cfgs(2);
7807         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7808         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
7809         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7810
7811         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
7812         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7813         assert_eq!(res.htlc_minimum_msat, 1);
7814
7815         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7816         let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7817         assert_eq!(res.htlc_minimum_msat, 1);
7818 }
7819
7820 #[test]
7821 fn test_channel_update_has_correct_htlc_maximum_msat() {
7822         // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
7823         // Bolt 7 specifies that if present `htlc_maximum_msat`:
7824         // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
7825         // 90% of the `channel_value`.
7826         // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
7827
7828         let mut config_30_percent = UserConfig::default();
7829         config_30_percent.channel_handshake_config.announced_channel = true;
7830         config_30_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
7831         let mut config_50_percent = UserConfig::default();
7832         config_50_percent.channel_handshake_config.announced_channel = true;
7833         config_50_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
7834         let mut config_95_percent = UserConfig::default();
7835         config_95_percent.channel_handshake_config.announced_channel = true;
7836         config_95_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
7837         let mut config_100_percent = UserConfig::default();
7838         config_100_percent.channel_handshake_config.announced_channel = true;
7839         config_100_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
7840
7841         let chanmon_cfgs = create_chanmon_cfgs(4);
7842         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
7843         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)]);
7844         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
7845
7846         let channel_value_satoshis = 100000;
7847         let channel_value_msat = channel_value_satoshis * 1000;
7848         let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
7849         let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
7850         let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
7851
7852         let (node_0_chan_update, node_1_chan_update, _, _)  = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value_satoshis, 10001);
7853         let (node_2_chan_update, node_3_chan_update, _, _)  = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, channel_value_satoshis, 10001);
7854
7855         // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
7856         // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
7857         assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, channel_value_50_percent_msat);
7858         // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
7859         // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
7860         assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, channel_value_30_percent_msat);
7861
7862         // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7863         // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
7864         // `channel_value`.
7865         assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7866         // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7867         // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
7868         // `channel_value`.
7869         assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7870 }
7871
7872 #[test]
7873 fn test_manually_accept_inbound_channel_request() {
7874         let mut manually_accept_conf = UserConfig::default();
7875         manually_accept_conf.manually_accept_inbound_channels = true;
7876         let chanmon_cfgs = create_chanmon_cfgs(2);
7877         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7878         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7879         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7880
7881         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7882         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7883
7884         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7885
7886         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7887         // accepting the inbound channel request.
7888         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7889
7890         let events = nodes[1].node.get_and_clear_pending_events();
7891         match events[0] {
7892                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7893                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
7894                 }
7895                 _ => panic!("Unexpected event"),
7896         }
7897
7898         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7899         assert_eq!(accept_msg_ev.len(), 1);
7900
7901         match accept_msg_ev[0] {
7902                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
7903                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7904                 }
7905                 _ => panic!("Unexpected event"),
7906         }
7907
7908         nodes[1].node.force_close_broadcasting_latest_txn(&temp_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7909
7910         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7911         assert_eq!(close_msg_ev.len(), 1);
7912
7913         let events = nodes[1].node.get_and_clear_pending_events();
7914         match events[0] {
7915                 Event::ChannelClosed { user_channel_id, .. } => {
7916                         assert_eq!(user_channel_id, 23);
7917                 }
7918                 _ => panic!("Unexpected event"),
7919         }
7920 }
7921
7922 #[test]
7923 fn test_manually_reject_inbound_channel_request() {
7924         let mut manually_accept_conf = UserConfig::default();
7925         manually_accept_conf.manually_accept_inbound_channels = true;
7926         let chanmon_cfgs = create_chanmon_cfgs(2);
7927         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7928         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7929         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7930
7931         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7932         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7933
7934         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7935
7936         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7937         // rejecting the inbound channel request.
7938         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7939
7940         let events = nodes[1].node.get_and_clear_pending_events();
7941         match events[0] {
7942                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7943                         nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7944                 }
7945                 _ => panic!("Unexpected event"),
7946         }
7947
7948         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7949         assert_eq!(close_msg_ev.len(), 1);
7950
7951         match close_msg_ev[0] {
7952                 MessageSendEvent::HandleError { ref node_id, .. } => {
7953                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7954                 }
7955                 _ => panic!("Unexpected event"),
7956         }
7957
7958         // There should be no more events to process, as the channel was never opened.
7959         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
7960 }
7961
7962 #[test]
7963 fn test_can_not_accept_inbound_channel_twice() {
7964         let mut manually_accept_conf = UserConfig::default();
7965         manually_accept_conf.manually_accept_inbound_channels = true;
7966         let chanmon_cfgs = create_chanmon_cfgs(2);
7967         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7968         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7969         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7970
7971         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7972         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7973
7974         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7975
7976         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7977         // accepting the inbound channel request.
7978         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7979
7980         let events = nodes[1].node.get_and_clear_pending_events();
7981         match events[0] {
7982                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7983                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
7984                         let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
7985                         match api_res {
7986                                 Err(APIError::APIMisuseError { err }) => {
7987                                         assert_eq!(err, "No such channel awaiting to be accepted.");
7988                                 },
7989                                 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
7990                                 Err(e) => panic!("Unexpected Error {:?}", e),
7991                         }
7992                 }
7993                 _ => panic!("Unexpected event"),
7994         }
7995
7996         // Ensure that the channel wasn't closed after attempting to accept it twice.
7997         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7998         assert_eq!(accept_msg_ev.len(), 1);
7999
8000         match accept_msg_ev[0] {
8001                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8002                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8003                 }
8004                 _ => panic!("Unexpected event"),
8005         }
8006 }
8007
8008 #[test]
8009 fn test_can_not_accept_unknown_inbound_channel() {
8010         let chanmon_cfg = create_chanmon_cfgs(2);
8011         let node_cfg = create_node_cfgs(2, &chanmon_cfg);
8012         let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
8013         let nodes = create_network(2, &node_cfg, &node_chanmgr);
8014
8015         let unknown_channel_id = ChannelId::new_zero();
8016         let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
8017         match api_res {
8018                 Err(APIError::APIMisuseError { err }) => {
8019                         assert_eq!(err, "No such channel awaiting to be accepted.");
8020                 },
8021                 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
8022                 Err(e) => panic!("Unexpected Error: {:?}", e),
8023         }
8024 }
8025
8026 #[test]
8027 fn test_onion_value_mpp_set_calculation() {
8028         // Test that we use the onion value `amt_to_forward` when
8029         // calculating whether we've reached the `total_msat` of an MPP
8030         // by having a routing node forward more than `amt_to_forward`
8031         // and checking that the receiving node doesn't generate
8032         // a PaymentClaimable event too early
8033         let node_count = 4;
8034         let chanmon_cfgs = create_chanmon_cfgs(node_count);
8035         let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
8036         let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
8037         let mut nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
8038
8039         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8040         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
8041         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
8042         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
8043
8044         let total_msat = 100_000;
8045         let expected_paths: &[&[&Node]] = &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]];
8046         let (mut route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], total_msat);
8047         let sample_path = route.paths.pop().unwrap();
8048
8049         let mut path_1 = sample_path.clone();
8050         path_1.hops[0].pubkey = nodes[1].node.get_our_node_id();
8051         path_1.hops[0].short_channel_id = chan_1_id;
8052         path_1.hops[1].pubkey = nodes[3].node.get_our_node_id();
8053         path_1.hops[1].short_channel_id = chan_3_id;
8054         path_1.hops[1].fee_msat = 100_000;
8055         route.paths.push(path_1);
8056
8057         let mut path_2 = sample_path.clone();
8058         path_2.hops[0].pubkey = nodes[2].node.get_our_node_id();
8059         path_2.hops[0].short_channel_id = chan_2_id;
8060         path_2.hops[1].pubkey = nodes[3].node.get_our_node_id();
8061         path_2.hops[1].short_channel_id = chan_4_id;
8062         path_2.hops[1].fee_msat = 1_000;
8063         route.paths.push(path_2);
8064
8065         // Send payment
8066         let payment_id = PaymentId(nodes[0].keys_manager.backing.get_secure_random_bytes());
8067         let onion_session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
8068                 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &route).unwrap();
8069         nodes[0].node.test_send_payment_internal(&route, our_payment_hash,
8070                 RecipientOnionFields::secret_only(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
8071         check_added_monitors!(nodes[0], expected_paths.len());
8072
8073         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8074         assert_eq!(events.len(), expected_paths.len());
8075
8076         // First path
8077         let ev = remove_first_msg_event_to_node(&expected_paths[0][0].node.get_our_node_id(), &mut events);
8078         let mut payment_event = SendEvent::from_event(ev);
8079         let mut prev_node = &nodes[0];
8080
8081         for (idx, &node) in expected_paths[0].iter().enumerate() {
8082                 assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
8083
8084                 if idx == 0 { // routing node
8085                         let session_priv = [3; 32];
8086                         let height = nodes[0].best_block_info().1;
8087                         let session_priv = SecretKey::from_slice(&session_priv).unwrap();
8088                         let mut onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
8089                         let (mut onion_payloads, _, _) = onion_utils::build_onion_payloads(&route.paths[0], 100_000,
8090                                 RecipientOnionFields::secret_only(our_payment_secret), height + 1, &None).unwrap();
8091                         // Edit amt_to_forward to simulate the sender having set
8092                         // the final amount and the routing node taking less fee
8093                         if let msgs::OutboundOnionPayload::Receive { ref mut amt_msat, .. } = onion_payloads[1] {
8094                                 *amt_msat = 99_000;
8095                         } else { panic!() }
8096                         let new_onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash).unwrap();
8097                         payment_event.msgs[0].onion_routing_packet = new_onion_packet;
8098                 }
8099
8100                 node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]);
8101                 check_added_monitors!(node, 0);
8102                 commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
8103                 expect_pending_htlcs_forwardable!(node);
8104
8105                 if idx == 0 {
8106                         let mut events_2 = node.node.get_and_clear_pending_msg_events();
8107                         assert_eq!(events_2.len(), 1);
8108                         check_added_monitors!(node, 1);
8109                         payment_event = SendEvent::from_event(events_2.remove(0));
8110                         assert_eq!(payment_event.msgs.len(), 1);
8111                 } else {
8112                         let events_2 = node.node.get_and_clear_pending_events();
8113                         assert!(events_2.is_empty());
8114                 }
8115
8116                 prev_node = node;
8117         }
8118
8119         // Second path
8120         let ev = remove_first_msg_event_to_node(&expected_paths[1][0].node.get_our_node_id(), &mut events);
8121         pass_along_path(&nodes[0], expected_paths[1], 101_000, our_payment_hash.clone(), Some(our_payment_secret), ev, true, None);
8122
8123         claim_payment_along_route(&nodes[0], expected_paths, false, our_payment_preimage);
8124 }
8125
8126 fn do_test_overshoot_mpp(msat_amounts: &[u64], total_msat: u64) {
8127
8128         let routing_node_count = msat_amounts.len();
8129         let node_count = routing_node_count + 2;
8130
8131         let chanmon_cfgs = create_chanmon_cfgs(node_count);
8132         let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
8133         let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
8134         let nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
8135
8136         let src_idx = 0;
8137         let dst_idx = 1;
8138
8139         // Create channels for each amount
8140         let mut expected_paths = Vec::with_capacity(routing_node_count);
8141         let mut src_chan_ids = Vec::with_capacity(routing_node_count);
8142         let mut dst_chan_ids = Vec::with_capacity(routing_node_count);
8143         for i in 0..routing_node_count {
8144                 let routing_node = 2 + i;
8145                 let src_chan_id = create_announced_chan_between_nodes(&nodes, src_idx, routing_node).0.contents.short_channel_id;
8146                 src_chan_ids.push(src_chan_id);
8147                 let dst_chan_id = create_announced_chan_between_nodes(&nodes, routing_node, dst_idx).0.contents.short_channel_id;
8148                 dst_chan_ids.push(dst_chan_id);
8149                 let path = vec![&nodes[routing_node], &nodes[dst_idx]];
8150                 expected_paths.push(path);
8151         }
8152         let expected_paths: Vec<&[&Node]> = expected_paths.iter().map(|route| route.as_slice()).collect();
8153
8154         // Create a route for each amount
8155         let example_amount = 100000;
8156         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);
8157         let sample_path = route.paths.pop().unwrap();
8158         for i in 0..routing_node_count {
8159                 let routing_node = 2 + i;
8160                 let mut path = sample_path.clone();
8161                 path.hops[0].pubkey = nodes[routing_node].node.get_our_node_id();
8162                 path.hops[0].short_channel_id = src_chan_ids[i];
8163                 path.hops[1].pubkey = nodes[dst_idx].node.get_our_node_id();
8164                 path.hops[1].short_channel_id = dst_chan_ids[i];
8165                 path.hops[1].fee_msat = msat_amounts[i];
8166                 route.paths.push(path);
8167         }
8168
8169         // Send payment with manually set total_msat
8170         let payment_id = PaymentId(nodes[src_idx].keys_manager.backing.get_secure_random_bytes());
8171         let onion_session_privs = nodes[src_idx].node.test_add_new_pending_payment(our_payment_hash,
8172                 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &route).unwrap();
8173         nodes[src_idx].node.test_send_payment_internal(&route, our_payment_hash,
8174                 RecipientOnionFields::secret_only(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
8175         check_added_monitors!(nodes[src_idx], expected_paths.len());
8176
8177         let mut events = nodes[src_idx].node.get_and_clear_pending_msg_events();
8178         assert_eq!(events.len(), expected_paths.len());
8179         let mut amount_received = 0;
8180         for (path_idx, expected_path) in expected_paths.iter().enumerate() {
8181                 let ev = remove_first_msg_event_to_node(&expected_path[0].node.get_our_node_id(), &mut events);
8182
8183                 let current_path_amount = msat_amounts[path_idx];
8184                 amount_received += current_path_amount;
8185                 let became_claimable_now = amount_received >= total_msat && amount_received - current_path_amount < total_msat;
8186                 pass_along_path(&nodes[src_idx], expected_path, amount_received, our_payment_hash.clone(), Some(our_payment_secret), ev, became_claimable_now, None);
8187         }
8188
8189         claim_payment_along_route(&nodes[src_idx], &expected_paths, false, our_payment_preimage);
8190 }
8191
8192 #[test]
8193 fn test_overshoot_mpp() {
8194         do_test_overshoot_mpp(&[100_000, 101_000], 200_000);
8195         do_test_overshoot_mpp(&[100_000, 10_000, 100_000], 200_000);
8196 }
8197
8198 #[test]
8199 fn test_simple_mpp() {
8200         // Simple test of sending a multi-path payment.
8201         let chanmon_cfgs = create_chanmon_cfgs(4);
8202         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8203         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8204         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8205
8206         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8207         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
8208         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
8209         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
8210
8211         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8212         let path = route.paths[0].clone();
8213         route.paths.push(path);
8214         route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
8215         route.paths[0].hops[0].short_channel_id = chan_1_id;
8216         route.paths[0].hops[1].short_channel_id = chan_3_id;
8217         route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
8218         route.paths[1].hops[0].short_channel_id = chan_2_id;
8219         route.paths[1].hops[1].short_channel_id = chan_4_id;
8220         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8221         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8222 }
8223
8224 #[test]
8225 fn test_preimage_storage() {
8226         // Simple test of payment preimage storage allowing no client-side storage to claim payments
8227         let chanmon_cfgs = create_chanmon_cfgs(2);
8228         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8229         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8230         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8231
8232         create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8233
8234         {
8235                 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200, None).unwrap();
8236                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8237                 nodes[0].node.send_payment_with_route(&route, payment_hash,
8238                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
8239                 check_added_monitors!(nodes[0], 1);
8240                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8241                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8242                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8243                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8244         }
8245         // Note that after leaving the above scope we have no knowledge of any arguments or return
8246         // values from previous calls.
8247         expect_pending_htlcs_forwardable!(nodes[1]);
8248         let events = nodes[1].node.get_and_clear_pending_events();
8249         assert_eq!(events.len(), 1);
8250         match events[0] {
8251                 Event::PaymentClaimable { ref purpose, .. } => {
8252                         match &purpose {
8253                                 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
8254                                         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8255                                 },
8256                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
8257                         }
8258                 },
8259                 _ => panic!("Unexpected event"),
8260         }
8261 }
8262
8263 #[test]
8264 fn test_bad_secret_hash() {
8265         // Simple test of unregistered payment hash/invalid payment secret handling
8266         let chanmon_cfgs = create_chanmon_cfgs(2);
8267         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8268         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8269         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8270
8271         create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8272
8273         let random_payment_hash = PaymentHash([42; 32]);
8274         let random_payment_secret = PaymentSecret([43; 32]);
8275         let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2, None).unwrap();
8276         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8277
8278         // All the below cases should end up being handled exactly identically, so we macro the
8279         // resulting events.
8280         macro_rules! handle_unknown_invalid_payment_data {
8281                 ($payment_hash: expr) => {
8282                         check_added_monitors!(nodes[0], 1);
8283                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8284                         let payment_event = SendEvent::from_event(events.pop().unwrap());
8285                         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8286                         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8287
8288                         // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8289                         // again to process the pending backwards-failure of the HTLC
8290                         expect_pending_htlcs_forwardable!(nodes[1]);
8291                         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment{ payment_hash: $payment_hash }]);
8292                         check_added_monitors!(nodes[1], 1);
8293
8294                         // We should fail the payment back
8295                         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8296                         match events.pop().unwrap() {
8297                                 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8298                                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8299                                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8300                                 },
8301                                 _ => panic!("Unexpected event"),
8302                         }
8303                 }
8304         }
8305
8306         let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8307         // Error data is the HTLC value (100,000) and current block height
8308         let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8309
8310         // Send a payment with the right payment hash but the wrong payment secret
8311         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
8312                 RecipientOnionFields::secret_only(random_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
8313         handle_unknown_invalid_payment_data!(our_payment_hash);
8314         expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8315
8316         // Send a payment with a random payment hash, but the right payment secret
8317         nodes[0].node.send_payment_with_route(&route, random_payment_hash,
8318                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8319         handle_unknown_invalid_payment_data!(random_payment_hash);
8320         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8321
8322         // Send a payment with a random payment hash and random payment secret
8323         nodes[0].node.send_payment_with_route(&route, random_payment_hash,
8324                 RecipientOnionFields::secret_only(random_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8325         handle_unknown_invalid_payment_data!(random_payment_hash);
8326         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8327 }
8328
8329 #[test]
8330 fn test_update_err_monitor_lockdown() {
8331         // Our monitor will lock update of local commitment transaction if a broadcastion condition
8332         // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8333         // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateStatus
8334         // error.
8335         //
8336         // This scenario may happen in a watchtower setup, where watchtower process a block height
8337         // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8338         // commitment at same time.
8339
8340         let chanmon_cfgs = create_chanmon_cfgs(2);
8341         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8342         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8343         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8344
8345         // Create some initial channel
8346         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8347         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8348
8349         // Rebalance the network to generate htlc in the two directions
8350         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8351
8352         // Route a HTLC from node 0 to node 1 (but don't settle)
8353         let (preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
8354
8355         // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8356         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8357         let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8358         let persister = test_utils::TestPersister::new();
8359         let watchtower = {
8360                 let new_monitor = {
8361                         let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8362                         let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<TestChannelSigner>)>::read(
8363                                         &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8364                         assert!(new_monitor == *monitor);
8365                         new_monitor
8366                 };
8367                 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);
8368                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8369                 watchtower
8370         };
8371         let block = create_dummy_block(BlockHash::all_zeros(), 42, Vec::new());
8372         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8373         // transaction lock time requirements here.
8374         chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 200));
8375         watchtower.chain_monitor.block_connected(&block, 200);
8376
8377         // Try to update ChannelMonitor
8378         nodes[1].node.claim_funds(preimage);
8379         check_added_monitors!(nodes[1], 1);
8380         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
8381
8382         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8383         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8384         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8385         {
8386                 let mut node_0_per_peer_lock;
8387                 let mut node_0_peer_state_lock;
8388                 let mut channel = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1.2);
8389                 if let Ok(Some(update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8390                         assert_eq!(watchtower.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::PermanentFailure);
8391                         assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8392                 } else { assert!(false); }
8393         }
8394         // Our local monitor is in-sync and hasn't processed yet timeout
8395         check_added_monitors!(nodes[0], 1);
8396         let events = nodes[0].node.get_and_clear_pending_events();
8397         assert_eq!(events.len(), 1);
8398 }
8399
8400 #[test]
8401 fn test_concurrent_monitor_claim() {
8402         // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8403         // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8404         // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8405         // state N+1 confirms. Alice claims output from state N+1.
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         route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8421
8422         // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8423         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8424         let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8425         let persister = test_utils::TestPersister::new();
8426         let alice_broadcaster = test_utils::TestBroadcaster::with_blocks(
8427                 Arc::new(Mutex::new(nodes[0].blocks.lock().unwrap().clone())),
8428         );
8429         let watchtower_alice = {
8430                 let new_monitor = {
8431                         let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8432                         let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<TestChannelSigner>)>::read(
8433                                         &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8434                         assert!(new_monitor == *monitor);
8435                         new_monitor
8436                 };
8437                 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &alice_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8438                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8439                 watchtower
8440         };
8441         let block = create_dummy_block(BlockHash::all_zeros(), 42, Vec::new());
8442         // Make Alice aware of enough blocks that it doesn't think we're violating transaction lock time
8443         // requirements here.
8444         const HTLC_TIMEOUT_BROADCAST: u32 = CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS;
8445         alice_broadcaster.blocks.lock().unwrap().resize((HTLC_TIMEOUT_BROADCAST) as usize, (block.clone(), HTLC_TIMEOUT_BROADCAST));
8446         watchtower_alice.chain_monitor.block_connected(&block, HTLC_TIMEOUT_BROADCAST);
8447
8448         // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8449         let alice_state = {
8450                 let mut txn = alice_broadcaster.txn_broadcast();
8451                 assert_eq!(txn.len(), 2);
8452                 txn.remove(0)
8453         };
8454
8455         // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8456         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8457         let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8458         let persister = test_utils::TestPersister::new();
8459         let bob_broadcaster = test_utils::TestBroadcaster::with_blocks(Arc::clone(&alice_broadcaster.blocks));
8460         let watchtower_bob = {
8461                 let new_monitor = {
8462                         let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8463                         let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<TestChannelSigner>)>::read(
8464                                         &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8465                         assert!(new_monitor == *monitor);
8466                         new_monitor
8467                 };
8468                 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &bob_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8469                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8470                 watchtower
8471         };
8472         watchtower_bob.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, Vec::new()), HTLC_TIMEOUT_BROADCAST - 1);
8473
8474         // Route another payment to generate another update with still previous HTLC pending
8475         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8476         nodes[1].node.send_payment_with_route(&route, payment_hash,
8477                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
8478         check_added_monitors!(nodes[1], 1);
8479
8480         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8481         assert_eq!(updates.update_add_htlcs.len(), 1);
8482         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8483         {
8484                 let mut node_0_per_peer_lock;
8485                 let mut node_0_peer_state_lock;
8486                 let mut channel = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1.2);
8487                 if let Ok(Some(update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8488                         // Watchtower Alice should already have seen the block and reject the update
8489                         assert_eq!(watchtower_alice.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::PermanentFailure);
8490                         assert_eq!(watchtower_bob.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8491                         assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8492                 } else { assert!(false); }
8493         }
8494         // Our local monitor is in-sync and hasn't processed yet timeout
8495         check_added_monitors!(nodes[0], 1);
8496
8497         //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8498         watchtower_bob.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, Vec::new()), HTLC_TIMEOUT_BROADCAST);
8499
8500         // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8501         let bob_state_y;
8502         {
8503                 let mut txn = bob_broadcaster.txn_broadcast();
8504                 assert_eq!(txn.len(), 2);
8505                 bob_state_y = txn.remove(0);
8506         };
8507
8508         // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8509         let height = HTLC_TIMEOUT_BROADCAST + 1;
8510         connect_blocks(&nodes[0], height - nodes[0].best_block_info().1);
8511         check_closed_broadcast(&nodes[0], 1, true);
8512         check_closed_event!(&nodes[0], 1, ClosureReason::CommitmentTxConfirmed, false,
8513                 [nodes[1].node.get_our_node_id()], 100000);
8514         watchtower_alice.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, vec![bob_state_y.clone()]), height);
8515         check_added_monitors(&nodes[0], 1);
8516         {
8517                 let htlc_txn = alice_broadcaster.txn_broadcast();
8518                 assert_eq!(htlc_txn.len(), 2);
8519                 check_spends!(htlc_txn[0], bob_state_y);
8520                 // Alice doesn't clean up the old HTLC claim since it hasn't seen a conflicting spend for
8521                 // it. However, she should, because it now has an invalid parent.
8522                 check_spends!(htlc_txn[1], alice_state);
8523         }
8524 }
8525
8526 #[test]
8527 fn test_pre_lockin_no_chan_closed_update() {
8528         // Test that if a peer closes a channel in response to a funding_created message we don't
8529         // generate a channel update (as the channel cannot appear on chain without a funding_signed
8530         // message).
8531         //
8532         // Doing so would imply a channel monitor update before the initial channel monitor
8533         // registration, violating our API guarantees.
8534         //
8535         // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8536         // then opening a second channel with the same funding output as the first (which is not
8537         // rejected because the first channel does not exist in the ChannelManager) and closing it
8538         // before receiving funding_signed.
8539         let chanmon_cfgs = create_chanmon_cfgs(2);
8540         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8541         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8542         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8543
8544         // Create an initial channel
8545         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8546         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8547         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8548         let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8549         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
8550
8551         // Move the first channel through the funding flow...
8552         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8553
8554         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8555         check_added_monitors!(nodes[0], 0);
8556
8557         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8558         let channel_id = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8559         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8560         assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8561         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("Hi".to_string()) }, true,
8562                 [nodes[1].node.get_our_node_id(); 2], 100000);
8563 }
8564
8565 #[test]
8566 fn test_htlc_no_detection() {
8567         // This test is a mutation to underscore the detection logic bug we had
8568         // before #653. HTLC value routed is above the remaining balance, thus
8569         // inverting HTLC and `to_remote` output. HTLC will come second and
8570         // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8571         // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8572         // outputs order detection for correct spending children filtring.
8573
8574         let chanmon_cfgs = create_chanmon_cfgs(2);
8575         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8576         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8577         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8578
8579         // Create some initial channels
8580         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8581
8582         send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8583         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8584         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8585         assert_eq!(local_txn[0].input.len(), 1);
8586         assert_eq!(local_txn[0].output.len(), 3);
8587         check_spends!(local_txn[0], chan_1.3);
8588
8589         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8590         let block = create_dummy_block(nodes[0].best_block_hash(), 42, vec![local_txn[0].clone()]);
8591         connect_block(&nodes[0], &block);
8592         // We deliberately connect the local tx twice as this should provoke a failure calling
8593         // this test before #653 fix.
8594         chain::Listen::block_connected(&nodes[0].chain_monitor.chain_monitor, &block, nodes[0].best_block_info().1 + 1);
8595         check_closed_broadcast!(nodes[0], true);
8596         check_added_monitors!(nodes[0], 1);
8597         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
8598         connect_blocks(&nodes[0], TEST_FINAL_CLTV);
8599
8600         let htlc_timeout = {
8601                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8602                 assert_eq!(node_txn.len(), 1);
8603                 assert_eq!(node_txn[0].input.len(), 1);
8604                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8605                 check_spends!(node_txn[0], local_txn[0]);
8606                 node_txn[0].clone()
8607         };
8608
8609         connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![htlc_timeout.clone()]));
8610         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8611         expect_payment_failed!(nodes[0], our_payment_hash, false);
8612 }
8613
8614 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8615         // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8616         // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8617         // Carol, Alice would be the upstream node, and Carol the downstream.)
8618         //
8619         // Steps of the test:
8620         // 1) Alice sends a HTLC to Carol through Bob.
8621         // 2) Carol doesn't settle the HTLC.
8622         // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8623         // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8624         // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8625         //    but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8626         // 5) Carol release the preimage to Bob off-chain.
8627         // 6) Bob claims the offered output on the broadcasted commitment.
8628         let chanmon_cfgs = create_chanmon_cfgs(3);
8629         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8630         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8631         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8632
8633         // Create some initial channels
8634         let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8635         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001);
8636
8637         // Steps (1) and (2):
8638         // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8639         let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
8640
8641         // Check that Alice's commitment transaction now contains an output for this HTLC.
8642         let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8643         check_spends!(alice_txn[0], chan_ab.3);
8644         assert_eq!(alice_txn[0].output.len(), 2);
8645         check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8646         assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8647         assert_eq!(alice_txn.len(), 2);
8648
8649         // Steps (3) and (4):
8650         // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8651         // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8652         let mut force_closing_node = 0; // Alice force-closes
8653         let mut counterparty_node = 1; // Bob if Alice force-closes
8654
8655         // Bob force-closes
8656         if !broadcast_alice {
8657                 force_closing_node = 1;
8658                 counterparty_node = 0;
8659         }
8660         nodes[force_closing_node].node.force_close_broadcasting_latest_txn(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id()).unwrap();
8661         check_closed_broadcast!(nodes[force_closing_node], true);
8662         check_added_monitors!(nodes[force_closing_node], 1);
8663         check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed, [nodes[counterparty_node].node.get_our_node_id()], 100000);
8664         if go_onchain_before_fulfill {
8665                 let txn_to_broadcast = match broadcast_alice {
8666                         true => alice_txn.clone(),
8667                         false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8668                 };
8669                 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![txn_to_broadcast[0].clone()]));
8670                 if broadcast_alice {
8671                         check_closed_broadcast!(nodes[1], true);
8672                         check_added_monitors!(nodes[1], 1);
8673                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
8674                 }
8675         }
8676
8677         // Step (5):
8678         // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8679         // process of removing the HTLC from their commitment transactions.
8680         nodes[2].node.claim_funds(payment_preimage);
8681         check_added_monitors!(nodes[2], 1);
8682         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
8683
8684         let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8685         assert!(carol_updates.update_add_htlcs.is_empty());
8686         assert!(carol_updates.update_fail_htlcs.is_empty());
8687         assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8688         assert!(carol_updates.update_fee.is_none());
8689         assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8690
8691         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8692         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false, false);
8693         // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8694         if !go_onchain_before_fulfill && broadcast_alice {
8695                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8696                 assert_eq!(events.len(), 1);
8697                 match events[0] {
8698                         MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8699                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8700                         },
8701                         _ => panic!("Unexpected event"),
8702                 };
8703         }
8704         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8705         // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8706         // Carol<->Bob's updated commitment transaction info.
8707         check_added_monitors!(nodes[1], 2);
8708
8709         let events = nodes[1].node.get_and_clear_pending_msg_events();
8710         assert_eq!(events.len(), 2);
8711         let bob_revocation = match events[0] {
8712                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8713                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8714                         (*msg).clone()
8715                 },
8716                 _ => panic!("Unexpected event"),
8717         };
8718         let bob_updates = match events[1] {
8719                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8720                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8721                         (*updates).clone()
8722                 },
8723                 _ => panic!("Unexpected event"),
8724         };
8725
8726         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8727         check_added_monitors!(nodes[2], 1);
8728         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8729         check_added_monitors!(nodes[2], 1);
8730
8731         let events = nodes[2].node.get_and_clear_pending_msg_events();
8732         assert_eq!(events.len(), 1);
8733         let carol_revocation = match events[0] {
8734                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8735                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8736                         (*msg).clone()
8737                 },
8738                 _ => panic!("Unexpected event"),
8739         };
8740         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8741         check_added_monitors!(nodes[1], 1);
8742
8743         // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8744         // here's where we put said channel's commitment tx on-chain.
8745         let mut txn_to_broadcast = alice_txn.clone();
8746         if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8747         if !go_onchain_before_fulfill {
8748                 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![txn_to_broadcast[0].clone()]));
8749                 // If Bob was the one to force-close, he will have already passed these checks earlier.
8750                 if broadcast_alice {
8751                         check_closed_broadcast!(nodes[1], true);
8752                         check_added_monitors!(nodes[1], 1);
8753                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
8754                 }
8755                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8756                 if broadcast_alice {
8757                         assert_eq!(bob_txn.len(), 1);
8758                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
8759                 } else {
8760                         assert_eq!(bob_txn.len(), 2);
8761                         check_spends!(bob_txn[0], chan_ab.3);
8762                 }
8763         }
8764
8765         // Step (6):
8766         // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8767         // broadcasted commitment transaction.
8768         {
8769                 let script_weight = match broadcast_alice {
8770                         true => OFFERED_HTLC_SCRIPT_WEIGHT,
8771                         false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8772                 };
8773                 // If Alice force-closed, Bob only broadcasts a HTLC-output-claiming transaction. Otherwise,
8774                 // Bob force-closed and broadcasts the commitment transaction along with a
8775                 // HTLC-output-claiming transaction.
8776                 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8777                 if broadcast_alice {
8778                         assert_eq!(bob_txn.len(), 1);
8779                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
8780                         assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8781                 } else {
8782                         assert_eq!(bob_txn.len(), 2);
8783                         check_spends!(bob_txn[1], txn_to_broadcast[0]);
8784                         assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8785                 }
8786         }
8787 }
8788
8789 #[test]
8790 fn test_onchain_htlc_settlement_after_close() {
8791         do_test_onchain_htlc_settlement_after_close(true, true);
8792         do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8793         do_test_onchain_htlc_settlement_after_close(true, false);
8794         do_test_onchain_htlc_settlement_after_close(false, false);
8795 }
8796
8797 #[test]
8798 fn test_duplicate_temporary_channel_id_from_different_peers() {
8799         // Tests that we can accept two different `OpenChannel` requests with the same
8800         // `temporary_channel_id`, as long as they are from different peers.
8801         let chanmon_cfgs = create_chanmon_cfgs(3);
8802         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8803         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8804         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8805
8806         // Create an first channel channel
8807         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8808         let mut open_chan_msg_chan_1_0 = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8809
8810         // Create an second channel
8811         nodes[2].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 43, None).unwrap();
8812         let mut open_chan_msg_chan_2_0 = get_event_msg!(nodes[2], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8813
8814         // Modify the `OpenChannel` from `nodes[2]` to `nodes[0]` to ensure that it uses the same
8815         // `temporary_channel_id` as the `OpenChannel` from nodes[1] to nodes[0].
8816         open_chan_msg_chan_2_0.temporary_channel_id = open_chan_msg_chan_1_0.temporary_channel_id;
8817
8818         // Assert that `nodes[0]` can accept both `OpenChannel` requests, even though they use the same
8819         // `temporary_channel_id` as they are from different peers.
8820         nodes[0].node.handle_open_channel(&nodes[1].node.get_our_node_id(), &open_chan_msg_chan_1_0);
8821         {
8822                 let events = nodes[0].node.get_and_clear_pending_msg_events();
8823                 assert_eq!(events.len(), 1);
8824                 match &events[0] {
8825                         MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8826                                 assert_eq!(node_id, &nodes[1].node.get_our_node_id());
8827                                 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8828                         },
8829                         _ => panic!("Unexpected event"),
8830                 }
8831         }
8832
8833         nodes[0].node.handle_open_channel(&nodes[2].node.get_our_node_id(), &open_chan_msg_chan_2_0);
8834         {
8835                 let events = nodes[0].node.get_and_clear_pending_msg_events();
8836                 assert_eq!(events.len(), 1);
8837                 match &events[0] {
8838                         MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8839                                 assert_eq!(node_id, &nodes[2].node.get_our_node_id());
8840                                 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8841                         },
8842                         _ => panic!("Unexpected event"),
8843                 }
8844         }
8845 }
8846
8847 #[test]
8848 fn test_duplicate_chan_id() {
8849         // Test that if a given peer tries to open a channel with the same channel_id as one that is
8850         // already open we reject it and keep the old channel.
8851         //
8852         // Previously, full_stack_target managed to figure out that if you tried to open two channels
8853         // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8854         // the existing channel when we detect the duplicate new channel, screwing up our monitor
8855         // updating logic for the existing channel.
8856         let chanmon_cfgs = create_chanmon_cfgs(2);
8857         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8858         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8859         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8860
8861         // Create an initial channel
8862         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8863         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8864         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8865         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()));
8866
8867         // Try to create a second channel with the same temporary_channel_id as the first and check
8868         // that it is rejected.
8869         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8870         {
8871                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8872                 assert_eq!(events.len(), 1);
8873                 match events[0] {
8874                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8875                                 // Technically, at this point, nodes[1] would be justified in thinking both the
8876                                 // first (valid) and second (invalid) channels are closed, given they both have
8877                                 // the same non-temporary channel_id. However, currently we do not, so we just
8878                                 // move forward with it.
8879                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8880                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8881                         },
8882                         _ => panic!("Unexpected event"),
8883                 }
8884         }
8885
8886         // Move the first channel through the funding flow...
8887         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8888
8889         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8890         check_added_monitors!(nodes[0], 0);
8891
8892         let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8893         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8894         {
8895                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
8896                 assert_eq!(added_monitors.len(), 1);
8897                 assert_eq!(added_monitors[0].0, funding_output);
8898                 added_monitors.clear();
8899         }
8900         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
8901
8902         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8903
8904         let funding_outpoint = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
8905         let channel_id = funding_outpoint.to_channel_id();
8906
8907         // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
8908         // temporary one).
8909
8910         // First try to open a second channel with a temporary channel id equal to the txid-based one.
8911         // Technically this is allowed by the spec, but we don't support it and there's little reason
8912         // to. Still, it shouldn't cause any other issues.
8913         open_chan_msg.temporary_channel_id = channel_id;
8914         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8915         {
8916                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8917                 assert_eq!(events.len(), 1);
8918                 match events[0] {
8919                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8920                                 // Technically, at this point, nodes[1] would be justified in thinking both
8921                                 // channels are closed, but currently we do not, so we just move forward with it.
8922                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8923                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8924                         },
8925                         _ => panic!("Unexpected event"),
8926                 }
8927         }
8928
8929         // Now try to create a second channel which has a duplicate funding output.
8930         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8931         let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8932         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_2_msg);
8933         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id()));
8934         create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
8935
8936         let (_, funding_created) = {
8937                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
8938                 let mut a_peer_state = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
8939                 // Once we call `get_funding_created` the channel has a duplicate channel_id as
8940                 // another channel in the ChannelManager - an invalid state. Thus, we'd panic later when we
8941                 // try to create another channel. Instead, we drop the channel entirely here (leaving the
8942                 // channelmanager in a possibly nonsense state instead).
8943                 let mut as_chan = a_peer_state.outbound_v1_channel_by_id.remove(&open_chan_2_msg.temporary_channel_id).unwrap();
8944                 let logger = test_utils::TestLogger::new();
8945                 as_chan.get_funding_created(tx.clone(), funding_outpoint, &&logger).map_err(|_| ()).unwrap()
8946         };
8947         check_added_monitors!(nodes[0], 0);
8948         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
8949         // At this point we'll look up if the channel_id is present and immediately fail the channel
8950         // without trying to persist the `ChannelMonitor`.
8951         check_added_monitors!(nodes[1], 0);
8952
8953         // ...still, nodes[1] will reject the duplicate channel.
8954         {
8955                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8956                 assert_eq!(events.len(), 1);
8957                 match events[0] {
8958                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8959                                 // Technically, at this point, nodes[1] would be justified in thinking both
8960                                 // channels are closed, but currently we do not, so we just move forward with it.
8961                                 assert_eq!(msg.channel_id, channel_id);
8962                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8963                         },
8964                         _ => panic!("Unexpected event"),
8965                 }
8966         }
8967
8968         // finally, finish creating the original channel and send a payment over it to make sure
8969         // everything is functional.
8970         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
8971         {
8972                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
8973                 assert_eq!(added_monitors.len(), 1);
8974                 assert_eq!(added_monitors[0].0, funding_output);
8975                 added_monitors.clear();
8976         }
8977         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
8978
8979         let events_4 = nodes[0].node.get_and_clear_pending_events();
8980         assert_eq!(events_4.len(), 0);
8981         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
8982         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
8983
8984         let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
8985         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
8986         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
8987
8988         send_payment(&nodes[0], &[&nodes[1]], 8000000);
8989 }
8990
8991 #[test]
8992 fn test_error_chans_closed() {
8993         // Test that we properly handle error messages, closing appropriate channels.
8994         //
8995         // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
8996         // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
8997         // we can test various edge cases around it to ensure we don't regress.
8998         let chanmon_cfgs = create_chanmon_cfgs(3);
8999         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9000         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9001         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9002
9003         // Create some initial channels
9004         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9005         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9006         let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
9007
9008         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9009         assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
9010         assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
9011
9012         // Closing a channel from a different peer has no effect
9013         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
9014         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9015
9016         // Closing one channel doesn't impact others
9017         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
9018         check_added_monitors!(nodes[0], 1);
9019         check_closed_broadcast!(nodes[0], false);
9020         check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) },
9021                 [nodes[1].node.get_our_node_id()], 100000);
9022         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
9023         assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
9024         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);
9025         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);
9026
9027         // A null channel ID should close all channels
9028         let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9029         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: ChannelId::new_zero(), data: "ERR".to_owned() });
9030         check_added_monitors!(nodes[0], 2);
9031         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) },
9032                 [nodes[1].node.get_our_node_id(); 2], 100000);
9033         let events = nodes[0].node.get_and_clear_pending_msg_events();
9034         assert_eq!(events.len(), 2);
9035         match events[0] {
9036                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9037                         assert_eq!(msg.contents.flags & 2, 2);
9038                 },
9039                 _ => panic!("Unexpected event"),
9040         }
9041         match events[1] {
9042                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9043                         assert_eq!(msg.contents.flags & 2, 2);
9044                 },
9045                 _ => panic!("Unexpected event"),
9046         }
9047         // Note that at this point users of a standard PeerHandler will end up calling
9048         // peer_disconnected.
9049         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9050         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9051
9052         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9053         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9054         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9055 }
9056
9057 #[test]
9058 fn test_invalid_funding_tx() {
9059         // Test that we properly handle invalid funding transactions sent to us from a peer.
9060         //
9061         // Previously, all other major lightning implementations had failed to properly sanitize
9062         // funding transactions from their counterparties, leading to a multi-implementation critical
9063         // security vulnerability (though we always sanitized properly, we've previously had
9064         // un-released crashes in the sanitization process).
9065         //
9066         // Further, if the funding transaction is consensus-valid, confirms, and is later spent, we'd
9067         // previously have crashed in `ChannelMonitor` even though we closed the channel as bogus and
9068         // gave up on it. We test this here by generating such a transaction.
9069         let chanmon_cfgs = create_chanmon_cfgs(2);
9070         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9071         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9072         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9073
9074         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
9075         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()));
9076         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()));
9077
9078         let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
9079
9080         // Create a witness program which can be spent by a 4-empty-stack-elements witness and which is
9081         // 136 bytes long. This matches our "accepted HTLC preimage spend" matching, previously causing
9082         // a panic as we'd try to extract a 32 byte preimage from a witness element without checking
9083         // its length.
9084         let mut wit_program: Vec<u8> = channelmonitor::deliberately_bogus_accepted_htlc_witness_program();
9085         let wit_program_script: Script = wit_program.into();
9086         for output in tx.output.iter_mut() {
9087                 // Make the confirmed funding transaction have a bogus script_pubkey
9088                 output.script_pubkey = Script::new_v0_p2wsh(&wit_program_script.wscript_hash());
9089         }
9090
9091         nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
9092         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()));
9093         check_added_monitors!(nodes[1], 1);
9094         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9095
9096         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()));
9097         check_added_monitors!(nodes[0], 1);
9098         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9099
9100         let events_1 = nodes[0].node.get_and_clear_pending_events();
9101         assert_eq!(events_1.len(), 0);
9102
9103         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9104         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9105         nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9106
9107         let expected_err = "funding tx had wrong script/value or output index";
9108         confirm_transaction_at(&nodes[1], &tx, 1);
9109         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() },
9110                 [nodes[0].node.get_our_node_id()], 100000);
9111         check_added_monitors!(nodes[1], 1);
9112         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9113         assert_eq!(events_2.len(), 1);
9114         if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9115                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9116                 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
9117                         assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
9118                 } else { panic!(); }
9119         } else { panic!(); }
9120         assert_eq!(nodes[1].node.list_channels().len(), 0);
9121
9122         // Now confirm a spend of the (bogus) funding transaction. As long as the witness is 5 elements
9123         // long the ChannelMonitor will try to read 32 bytes from the second-to-last element, panicing
9124         // as its not 32 bytes long.
9125         let mut spend_tx = Transaction {
9126                 version: 2i32, lock_time: PackedLockTime::ZERO,
9127                 input: tx.output.iter().enumerate().map(|(idx, _)| TxIn {
9128                         previous_output: BitcoinOutPoint {
9129                                 txid: tx.txid(),
9130                                 vout: idx as u32,
9131                         },
9132                         script_sig: Script::new(),
9133                         sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
9134                         witness: Witness::from_vec(channelmonitor::deliberately_bogus_accepted_htlc_witness())
9135                 }).collect(),
9136                 output: vec![TxOut {
9137                         value: 1000,
9138                         script_pubkey: Script::new(),
9139                 }]
9140         };
9141         check_spends!(spend_tx, tx);
9142         mine_transaction(&nodes[1], &spend_tx);
9143 }
9144
9145 #[test]
9146 fn test_coinbase_funding_tx() {
9147         // Miners are able to fund channels directly from coinbase transactions, however
9148         // by consensus rules, outputs of a coinbase transaction are encumbered by a 100
9149         // block maturity timelock. To ensure that a (non-0conf) channel like this is enforceable
9150         // on-chain, the minimum depth is updated to 100 blocks for coinbase funding transactions.
9151         //
9152         // Note that 0conf channels with coinbase funding transactions are unaffected and are
9153         // immediately operational after opening.
9154         let chanmon_cfgs = create_chanmon_cfgs(2);
9155         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9156         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9157         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9158
9159         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9160         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9161
9162         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
9163         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9164
9165         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
9166
9167         // Create the coinbase funding transaction.
9168         let (temporary_channel_id, tx, _) = create_coinbase_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
9169
9170         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9171         check_added_monitors!(nodes[0], 0);
9172         let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9173
9174         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
9175         check_added_monitors!(nodes[1], 1);
9176         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9177
9178         let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9179
9180         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
9181         check_added_monitors!(nodes[0], 1);
9182
9183         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9184         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
9185
9186         // Starting at height 0, we "confirm" the coinbase at height 1.
9187         confirm_transaction_at(&nodes[0], &tx, 1);
9188         // We connect 98 more blocks to have 99 confirmations for the coinbase transaction.
9189         connect_blocks(&nodes[0], COINBASE_MATURITY - 2);
9190         // Check that we have no pending message events (we have not queued a `channel_ready` yet).
9191         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
9192         // Now connect one more block which results in 100 confirmations of the coinbase transaction.
9193         connect_blocks(&nodes[0], 1);
9194         // There should now be a `channel_ready` which can be handled.
9195         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()));
9196
9197         confirm_transaction_at(&nodes[1], &tx, 1);
9198         connect_blocks(&nodes[1], COINBASE_MATURITY - 2);
9199         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
9200         connect_blocks(&nodes[1], 1);
9201         expect_channel_ready_event(&nodes[1], &nodes[0].node.get_our_node_id());
9202         create_chan_between_nodes_with_value_confirm_second(&nodes[0], &nodes[1]);
9203 }
9204
9205 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9206         // In the first version of the chain::Confirm interface, after a refactor was made to not
9207         // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9208         // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9209         // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9210         // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9211         // spending transaction until height N+1 (or greater). This was due to the way
9212         // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9213         // spending transaction at the height the input transaction was confirmed at, not whether we
9214         // should broadcast a spending transaction at the current height.
9215         // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9216         // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9217         // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9218         // until we learned about an additional block.
9219         //
9220         // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9221         // aren't broadcasting transactions too early (ie not broadcasting them at all).
9222         let chanmon_cfgs = create_chanmon_cfgs(3);
9223         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9224         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9225         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9226         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9227
9228         create_announced_chan_between_nodes(&nodes, 0, 1);
9229         let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
9230         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9231         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id());
9232         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9233
9234         nodes[1].node.force_close_broadcasting_latest_txn(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
9235         check_closed_broadcast!(nodes[1], true);
9236         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[2].node.get_our_node_id()], 100000);
9237         check_added_monitors!(nodes[1], 1);
9238         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9239         assert_eq!(node_txn.len(), 1);
9240
9241         let conf_height = nodes[1].best_block_info().1;
9242         if !test_height_before_timelock {
9243                 connect_blocks(&nodes[1], 24 * 6);
9244         }
9245         nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9246                 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9247         if test_height_before_timelock {
9248                 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9249                 // generate any events or broadcast any transactions
9250                 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9251                 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9252         } else {
9253                 // We should broadcast an HTLC transaction spending our funding transaction first
9254                 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9255                 assert_eq!(spending_txn.len(), 2);
9256                 assert_eq!(spending_txn[0].txid(), node_txn[0].txid());
9257                 check_spends!(spending_txn[1], node_txn[0]);
9258                 // We should also generate a SpendableOutputs event with the to_self output (as its
9259                 // timelock is up).
9260                 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9261                 assert_eq!(descriptor_spend_txn.len(), 1);
9262
9263                 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9264                 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9265                 // additional block built on top of the current chain.
9266                 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9267                         &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9268                 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 }]);
9269                 check_added_monitors!(nodes[1], 1);
9270
9271                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9272                 assert!(updates.update_add_htlcs.is_empty());
9273                 assert!(updates.update_fulfill_htlcs.is_empty());
9274                 assert_eq!(updates.update_fail_htlcs.len(), 1);
9275                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9276                 assert!(updates.update_fee.is_none());
9277                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9278                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9279                 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9280         }
9281 }
9282
9283 #[test]
9284 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9285         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9286         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9287 }
9288
9289 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
9290         let chanmon_cfgs = create_chanmon_cfgs(2);
9291         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9292         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9293         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9294
9295         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9296
9297         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
9298                 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
9299         let route = get_route!(nodes[0], payment_params, 10_000).unwrap();
9300
9301         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9302
9303         {
9304                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
9305                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
9306                 check_added_monitors!(nodes[0], 1);
9307                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9308                 assert_eq!(events.len(), 1);
9309                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9310                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9311                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9312         }
9313         expect_pending_htlcs_forwardable!(nodes[1]);
9314         expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9315
9316         {
9317                 // Note that we use a different PaymentId here to allow us to duplicativly pay
9318                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
9319                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_secret.0)).unwrap();
9320                 check_added_monitors!(nodes[0], 1);
9321                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9322                 assert_eq!(events.len(), 1);
9323                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9324                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9325                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9326                 // At this point, nodes[1] would notice it has too much value for the payment. It will
9327                 // assume the second is a privacy attack (no longer particularly relevant
9328                 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9329                 // the first HTLC delivered above.
9330         }
9331
9332         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9333         nodes[1].node.process_pending_htlc_forwards();
9334
9335         if test_for_second_fail_panic {
9336                 // Now we go fail back the first HTLC from the user end.
9337                 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9338
9339                 let expected_destinations = vec![
9340                         HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9341                         HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9342                 ];
9343                 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1],  expected_destinations);
9344                 nodes[1].node.process_pending_htlc_forwards();
9345
9346                 check_added_monitors!(nodes[1], 1);
9347                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9348                 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9349
9350                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9351                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9352                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9353
9354                 let failure_events = nodes[0].node.get_and_clear_pending_events();
9355                 assert_eq!(failure_events.len(), 4);
9356                 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9357                 if let Event::PaymentFailed { .. } = failure_events[1] {} else { panic!(); }
9358                 if let Event::PaymentPathFailed { .. } = failure_events[2] {} else { panic!(); }
9359                 if let Event::PaymentFailed { .. } = failure_events[3] {} else { panic!(); }
9360         } else {
9361                 // Let the second HTLC fail and claim the first
9362                 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9363                 nodes[1].node.process_pending_htlc_forwards();
9364
9365                 check_added_monitors!(nodes[1], 1);
9366                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9367                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9368                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9369
9370                 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new());
9371
9372                 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9373         }
9374 }
9375
9376 #[test]
9377 fn test_dup_htlc_second_fail_panic() {
9378         // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9379         // value for the payment, we'd fail back both HTLCs after generating a `PaymentClaimable` event.
9380         // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9381         // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9382         do_test_dup_htlc_second_rejected(true);
9383 }
9384
9385 #[test]
9386 fn test_dup_htlc_second_rejected() {
9387         // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9388         // simply reject the second HTLC but are still able to claim the first HTLC.
9389         do_test_dup_htlc_second_rejected(false);
9390 }
9391
9392 #[test]
9393 fn test_inconsistent_mpp_params() {
9394         // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9395         // such HTLC and allow the second to stay.
9396         let chanmon_cfgs = create_chanmon_cfgs(4);
9397         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9398         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9399         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9400
9401         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9402         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9403         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9404         let chan_2_3 =create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9405
9406         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
9407                 .with_bolt11_features(nodes[3].node.invoice_features()).unwrap();
9408         let mut route = get_route!(nodes[0], payment_params, 15_000_000).unwrap();
9409         assert_eq!(route.paths.len(), 2);
9410         route.paths.sort_by(|path_a, _| {
9411                 // Sort the path so that the path through nodes[1] comes first
9412                 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
9413                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9414         });
9415
9416         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9417
9418         let cur_height = nodes[0].best_block_info().1;
9419         let payment_id = PaymentId([42; 32]);
9420
9421         let session_privs = {
9422                 // We create a fake route here so that we start with three pending HTLCs, which we'll
9423                 // ultimately have, just not right away.
9424                 let mut dup_route = route.clone();
9425                 dup_route.paths.push(route.paths[1].clone());
9426                 nodes[0].node.test_add_new_pending_payment(our_payment_hash,
9427                         RecipientOnionFields::secret_only(our_payment_secret), payment_id, &dup_route).unwrap()
9428         };
9429         nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
9430                 RecipientOnionFields::secret_only(our_payment_secret), 15_000_000, cur_height, payment_id,
9431                 &None, session_privs[0]).unwrap();
9432         check_added_monitors!(nodes[0], 1);
9433
9434         {
9435                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9436                 assert_eq!(events.len(), 1);
9437                 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9438         }
9439         assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9440
9441         nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
9442                 RecipientOnionFields::secret_only(our_payment_secret), 14_000_000, cur_height, payment_id, &None, session_privs[1]).unwrap();
9443         check_added_monitors!(nodes[0], 1);
9444
9445         {
9446                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9447                 assert_eq!(events.len(), 1);
9448                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9449
9450                 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9451                 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9452
9453                 expect_pending_htlcs_forwardable!(nodes[2]);
9454                 check_added_monitors!(nodes[2], 1);
9455
9456                 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9457                 assert_eq!(events.len(), 1);
9458                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9459
9460                 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9461                 check_added_monitors!(nodes[3], 0);
9462                 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9463
9464                 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9465                 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9466                 // post-payment_secrets) and fail back the new HTLC.
9467         }
9468         expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9469         nodes[3].node.process_pending_htlc_forwards();
9470         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9471         nodes[3].node.process_pending_htlc_forwards();
9472
9473         check_added_monitors!(nodes[3], 1);
9474
9475         let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9476         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9477         commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9478
9479         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 }]);
9480         check_added_monitors!(nodes[2], 1);
9481
9482         let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9483         nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9484         commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9485
9486         expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9487
9488         nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
9489                 RecipientOnionFields::secret_only(our_payment_secret), 15_000_000, cur_height, payment_id,
9490                 &None, session_privs[2]).unwrap();
9491         check_added_monitors!(nodes[0], 1);
9492
9493         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9494         assert_eq!(events.len(), 1);
9495         pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9496
9497         do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9498         expect_payment_sent(&nodes[0], our_payment_preimage, Some(None), true, true);
9499 }
9500
9501 #[test]
9502 fn test_double_partial_claim() {
9503         // Test what happens if a node receives a payment, generates a PaymentClaimable event, the HTLCs
9504         // time out, the sender resends only some of the MPP parts, then the user processes the
9505         // PaymentClaimable event, ensuring they don't inadvertently claim only part of the full payment
9506         // amount.
9507         let chanmon_cfgs = create_chanmon_cfgs(4);
9508         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9509         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9510         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9511
9512         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9513         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9514         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9515         create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9516
9517         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
9518         assert_eq!(route.paths.len(), 2);
9519         route.paths.sort_by(|path_a, _| {
9520                 // Sort the path so that the path through nodes[1] comes first
9521                 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
9522                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9523         });
9524
9525         send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 15_000_000, payment_hash, payment_secret);
9526         // nodes[3] has now received a PaymentClaimable event...which it will take some (exorbitant)
9527         // amount of time to respond to.
9528
9529         // Connect some blocks to time out the payment
9530         connect_blocks(&nodes[3], TEST_FINAL_CLTV);
9531         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // To get the same height for sending later
9532
9533         let failed_destinations = vec![
9534                 HTLCDestination::FailedPayment { payment_hash },
9535                 HTLCDestination::FailedPayment { payment_hash },
9536         ];
9537         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations);
9538
9539         pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash, PaymentFailureReason::RecipientRejected);
9540
9541         // nodes[1] now retries one of the two paths...
9542         nodes[0].node.send_payment_with_route(&route, payment_hash,
9543                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9544         check_added_monitors!(nodes[0], 2);
9545
9546         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9547         assert_eq!(events.len(), 2);
9548         let node_1_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
9549         pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), node_1_msgs, false, None);
9550
9551         // At this point nodes[3] has received one half of the payment, and the user goes to handle
9552         // that PaymentClaimable event they got hours ago and never handled...we should refuse to claim.
9553         nodes[3].node.claim_funds(payment_preimage);
9554         check_added_monitors!(nodes[3], 0);
9555         assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
9556 }
9557
9558 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
9559 #[derive(Clone, Copy, PartialEq)]
9560 enum ExposureEvent {
9561         /// Breach occurs at HTLC forwarding (see `send_htlc`)
9562         AtHTLCForward,
9563         /// Breach occurs at HTLC reception (see `update_add_htlc`)
9564         AtHTLCReception,
9565         /// Breach occurs at outbound update_fee (see `send_update_fee`)
9566         AtUpdateFeeOutbound,
9567 }
9568
9569 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool, multiplier_dust_limit: bool) {
9570         // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
9571         // policy.
9572         //
9573         // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
9574         // trimmed-to-dust HTLC outbound balance and this new payment as included on next
9575         // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
9576         // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
9577         // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
9578         // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
9579         // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
9580         // might be available again for HTLC processing once the dust bandwidth has cleared up.
9581
9582         let chanmon_cfgs = create_chanmon_cfgs(2);
9583         let mut config = test_default_channel_config();
9584         config.channel_config.max_dust_htlc_exposure = if multiplier_dust_limit {
9585                 // Default test fee estimator rate is 253 sat/kw, so we set the multiplier to 5_000_000 / 253
9586                 // to get roughly the same initial value as the default setting when this test was
9587                 // originally written.
9588                 MaxDustHTLCExposure::FeeRateMultiplier(5_000_000 / 253)
9589         } else { MaxDustHTLCExposure::FixedLimitMsat(5_000_000) }; // initial default setting value
9590         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9591         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
9592         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9593
9594         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
9595         let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9596         open_channel.max_htlc_value_in_flight_msat = 50_000_000;
9597         open_channel.max_accepted_htlcs = 60;
9598         if on_holder_tx {
9599                 open_channel.dust_limit_satoshis = 546;
9600         }
9601         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
9602         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9603         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
9604
9605         let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
9606
9607         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
9608
9609         if on_holder_tx {
9610                 let mut node_0_per_peer_lock;
9611                 let mut node_0_peer_state_lock;
9612                 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);
9613                 chan.context.holder_dust_limit_satoshis = 546;
9614         }
9615
9616         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9617         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()));
9618         check_added_monitors!(nodes[1], 1);
9619         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9620
9621         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()));
9622         check_added_monitors!(nodes[0], 1);
9623         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9624
9625         let (channel_ready, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9626         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9627         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9628
9629         // Fetch a route in advance as we will be unable to once we're unable to send.
9630         let (mut route, payment_hash, _, payment_secret) =
9631                 get_route_and_payment_hash!(nodes[0], nodes[1], 1000);
9632
9633         let (dust_buffer_feerate, max_dust_htlc_exposure_msat) = {
9634                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
9635                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
9636                 let chan = chan_lock.channel_by_id.get(&channel_id).unwrap();
9637                 (chan.context.get_dust_buffer_feerate(None) as u64,
9638                 chan.context.get_max_dust_htlc_exposure_msat(&LowerBoundedFeeEstimator(nodes[0].fee_estimator)))
9639         };
9640         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;
9641         let dust_outbound_htlc_on_holder_tx: u64 = max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
9642
9643         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;
9644         let dust_inbound_htlc_on_holder_tx: u64 = max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
9645
9646         let dust_htlc_on_counterparty_tx: u64 = 4;
9647         let dust_htlc_on_counterparty_tx_msat: u64 = max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
9648
9649         if on_holder_tx {
9650                 if dust_outbound_balance {
9651                         // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9652                         // Outbound dust balance: 4372 sats
9653                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
9654                         for _ in 0..dust_outbound_htlc_on_holder_tx {
9655                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
9656                                 nodes[0].node.send_payment_with_route(&route, payment_hash,
9657                                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9658                         }
9659                 } else {
9660                         // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9661                         // Inbound dust balance: 4372 sats
9662                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
9663                         for _ in 0..dust_inbound_htlc_on_holder_tx {
9664                                 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
9665                         }
9666                 }
9667         } else {
9668                 if dust_outbound_balance {
9669                         // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9670                         // Outbound dust balance: 5000 sats
9671                         for _ in 0..dust_htlc_on_counterparty_tx - 1 {
9672                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
9673                                 nodes[0].node.send_payment_with_route(&route, payment_hash,
9674                                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9675                         }
9676                 } else {
9677                         // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9678                         // Inbound dust balance: 5000 sats
9679                         for _ in 0..dust_htlc_on_counterparty_tx - 1 {
9680                                 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
9681                         }
9682                 }
9683         }
9684
9685         if exposure_breach_event == ExposureEvent::AtHTLCForward {
9686                 route.paths[0].hops.last_mut().unwrap().fee_msat =
9687                         if on_holder_tx { dust_outbound_htlc_on_holder_tx_msat } else { dust_htlc_on_counterparty_tx_msat + 1 };
9688                 // With default dust exposure: 5000 sats
9689                 if on_holder_tx {
9690                         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
9691                                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
9692                                 ), true, APIError::ChannelUnavailable { .. }, {});
9693                 } else {
9694                         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
9695                                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
9696                                 ), true, APIError::ChannelUnavailable { .. }, {});
9697                 }
9698         } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
9699                 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 });
9700                 nodes[1].node.send_payment_with_route(&route, payment_hash,
9701                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9702                 check_added_monitors!(nodes[1], 1);
9703                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9704                 assert_eq!(events.len(), 1);
9705                 let payment_event = SendEvent::from_event(events.remove(0));
9706                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9707                 // With default dust exposure: 5000 sats
9708                 if on_holder_tx {
9709                         // Outbound dust balance: 6399 sats
9710                         let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
9711                         let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
9712                         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);
9713                 } else {
9714                         // Outbound dust balance: 5200 sats
9715                         nodes[0].logger.assert_log("lightning::ln::channel".to_string(),
9716                                 format!("Cannot accept value that would put our exposure to dust HTLCs at {} over the limit {} on counterparty commitment tx",
9717                                         dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx - 1) + dust_htlc_on_counterparty_tx_msat + 4,
9718                                         max_dust_htlc_exposure_msat), 1);
9719                 }
9720         } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
9721                 route.paths[0].hops.last_mut().unwrap().fee_msat = 2_500_000;
9722                 // For the multiplier dust exposure limit, since it scales with feerate,
9723                 // we need to add a lot of HTLCs that will become dust at the new feerate
9724                 // to cross the threshold.
9725                 for _ in 0..20 {
9726                         let (_, payment_hash, payment_secret) = get_payment_preimage_hash(&nodes[1], Some(1_000), None);
9727                         nodes[0].node.send_payment_with_route(&route, payment_hash,
9728                                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9729                 }
9730                 {
9731                         let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9732                         *feerate_lock = *feerate_lock * 10;
9733                 }
9734                 nodes[0].node.timer_tick_occurred();
9735                 check_added_monitors!(nodes[0], 1);
9736                 nodes[0].logger.assert_log_contains("lightning::ln::channel", "Cannot afford to send new feerate at 2530 without infringing max dust htlc exposure", 1);
9737         }
9738
9739         let _ = nodes[0].node.get_and_clear_pending_msg_events();
9740         let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9741         added_monitors.clear();
9742 }
9743
9744 fn do_test_max_dust_htlc_exposure_by_threshold_type(multiplier_dust_limit: bool) {
9745         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true, multiplier_dust_limit);
9746         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true, multiplier_dust_limit);
9747         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true, multiplier_dust_limit);
9748         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false, multiplier_dust_limit);
9749         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false, multiplier_dust_limit);
9750         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false, multiplier_dust_limit);
9751         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true, multiplier_dust_limit);
9752         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false, multiplier_dust_limit);
9753         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true, multiplier_dust_limit);
9754         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false, multiplier_dust_limit);
9755         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false, multiplier_dust_limit);
9756         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true, multiplier_dust_limit);
9757 }
9758
9759 #[test]
9760 fn test_max_dust_htlc_exposure() {
9761         do_test_max_dust_htlc_exposure_by_threshold_type(false);
9762         do_test_max_dust_htlc_exposure_by_threshold_type(true);
9763 }
9764
9765 #[test]
9766 fn test_non_final_funding_tx() {
9767         let chanmon_cfgs = create_chanmon_cfgs(2);
9768         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9769         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9770         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9771
9772         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
9773         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9774         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
9775         let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9776         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
9777
9778         let best_height = nodes[0].node.best_block.read().unwrap().height();
9779
9780         let chan_id = *nodes[0].network_chan_count.borrow();
9781         let events = nodes[0].node.get_and_clear_pending_events();
9782         let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::Script::new(), sequence: Sequence(1), witness: Witness::from_vec(vec!(vec!(1))) };
9783         assert_eq!(events.len(), 1);
9784         let mut tx = match events[0] {
9785                 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
9786                         // Timelock the transaction _beyond_ the best client height + 1.
9787                         Transaction { version: chan_id as i32, lock_time: PackedLockTime(best_height + 2), input: vec![input], output: vec![TxOut {
9788                                 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
9789                         }]}
9790                 },
9791                 _ => panic!("Unexpected event"),
9792         };
9793         // Transaction should fail as it's evaluated as non-final for propagation.
9794         match nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()) {
9795                 Err(APIError::APIMisuseError { err }) => {
9796                         assert_eq!(format!("Funding transaction absolute timelock is non-final"), err);
9797                 },
9798                 _ => panic!()
9799         }
9800
9801         // However, transaction should be accepted if it's in a +1 headroom from best block.
9802         tx.lock_time = PackedLockTime(tx.lock_time.0 - 1);
9803         assert!(nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
9804         get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9805 }
9806
9807 #[test]
9808 fn accept_busted_but_better_fee() {
9809         // If a peer sends us a fee update that is too low, but higher than our previous channel
9810         // feerate, we should accept it. In the future we may want to consider closing the channel
9811         // later, but for now we only accept the update.
9812         let mut chanmon_cfgs = create_chanmon_cfgs(2);
9813         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9814         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9815         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9816
9817         create_chan_between_nodes(&nodes[0], &nodes[1]);
9818
9819         // Set nodes[1] to expect 5,000 sat/kW.
9820         {
9821                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
9822                 *feerate_lock = 5000;
9823         }
9824
9825         // If nodes[0] increases their feerate, even if its not enough, nodes[1] should accept it.
9826         {
9827                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9828                 *feerate_lock = 1000;
9829         }
9830         nodes[0].node.timer_tick_occurred();
9831         check_added_monitors!(nodes[0], 1);
9832
9833         let events = nodes[0].node.get_and_clear_pending_msg_events();
9834         assert_eq!(events.len(), 1);
9835         match events[0] {
9836                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9837                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9838                         commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9839                 },
9840                 _ => panic!("Unexpected event"),
9841         };
9842
9843         // If nodes[0] increases their feerate further, even if its not enough, nodes[1] should accept
9844         // it.
9845         {
9846                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9847                 *feerate_lock = 2000;
9848         }
9849         nodes[0].node.timer_tick_occurred();
9850         check_added_monitors!(nodes[0], 1);
9851
9852         let events = nodes[0].node.get_and_clear_pending_msg_events();
9853         assert_eq!(events.len(), 1);
9854         match events[0] {
9855                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9856                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9857                         commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9858                 },
9859                 _ => panic!("Unexpected event"),
9860         };
9861
9862         // However, if nodes[0] decreases their feerate, nodes[1] should reject it and close the
9863         // channel.
9864         {
9865                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9866                 *feerate_lock = 1000;
9867         }
9868         nodes[0].node.timer_tick_occurred();
9869         check_added_monitors!(nodes[0], 1);
9870
9871         let events = nodes[0].node.get_and_clear_pending_msg_events();
9872         assert_eq!(events.len(), 1);
9873         match events[0] {
9874                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
9875                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9876                         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError {
9877                                 err: "Peer's feerate much too low. Actual: 1000. Our expected lower limit: 5000 (- 250)".to_owned() },
9878                                 [nodes[0].node.get_our_node_id()], 100000);
9879                         check_closed_broadcast!(nodes[1], true);
9880                         check_added_monitors!(nodes[1], 1);
9881                 },
9882                 _ => panic!("Unexpected event"),
9883         };
9884 }
9885
9886 fn do_payment_with_custom_min_final_cltv_expiry(valid_delta: bool, use_user_hash: bool) {
9887         let mut chanmon_cfgs = create_chanmon_cfgs(2);
9888         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9889         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9890         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9891         let min_final_cltv_expiry_delta = 120;
9892         let final_cltv_expiry_delta = if valid_delta { min_final_cltv_expiry_delta + 2 } else {
9893                 min_final_cltv_expiry_delta - 2 };
9894         let recv_value = 100_000;
9895
9896         create_chan_between_nodes(&nodes[0], &nodes[1]);
9897
9898         let payment_parameters = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), final_cltv_expiry_delta as u32);
9899         let (payment_hash, payment_preimage, payment_secret) = if use_user_hash {
9900                 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1],
9901                         Some(recv_value), Some(min_final_cltv_expiry_delta));
9902                 (payment_hash, payment_preimage, payment_secret)
9903         } else {
9904                 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(recv_value), 7200, Some(min_final_cltv_expiry_delta)).unwrap();
9905                 (payment_hash, nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap(), payment_secret)
9906         };
9907         let route = get_route!(nodes[0], payment_parameters, recv_value).unwrap();
9908         nodes[0].node.send_payment_with_route(&route, payment_hash,
9909                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9910         check_added_monitors!(nodes[0], 1);
9911         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9912         assert_eq!(events.len(), 1);
9913         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9914         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9915         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9916         expect_pending_htlcs_forwardable!(nodes[1]);
9917
9918         if valid_delta {
9919                 expect_payment_claimable!(nodes[1], payment_hash, payment_secret, recv_value, if use_user_hash {
9920                         None } else { Some(payment_preimage) }, nodes[1].node.get_our_node_id());
9921
9922                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
9923         } else {
9924                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
9925
9926                 check_added_monitors!(nodes[1], 1);
9927
9928                 let fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9929                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates.update_fail_htlcs[0]);
9930                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates.commitment_signed, false, true);
9931
9932                 expect_payment_failed!(nodes[0], payment_hash, true);
9933         }
9934 }
9935
9936 #[test]
9937 fn test_payment_with_custom_min_cltv_expiry_delta() {
9938         do_payment_with_custom_min_final_cltv_expiry(false, false);
9939         do_payment_with_custom_min_final_cltv_expiry(false, true);
9940         do_payment_with_custom_min_final_cltv_expiry(true, false);
9941         do_payment_with_custom_min_final_cltv_expiry(true, true);
9942 }
9943
9944 #[test]
9945 fn test_disconnects_peer_awaiting_response_ticks() {
9946         // Tests that nodes which are awaiting on a response critical for channel responsiveness
9947         // disconnect their counterparty after `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
9948         let mut chanmon_cfgs = create_chanmon_cfgs(2);
9949         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9950         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9951         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9952
9953         // Asserts a disconnect event is queued to the user.
9954         let check_disconnect_event = |node: &Node, should_disconnect: bool| {
9955                 let disconnect_event = node.node.get_and_clear_pending_msg_events().iter().find_map(|event|
9956                         if let MessageSendEvent::HandleError { action, .. } = event {
9957                                 if let msgs::ErrorAction::DisconnectPeerWithWarning { .. } = action {
9958                                         Some(())
9959                                 } else {
9960                                         None
9961                                 }
9962                         } else {
9963                                 None
9964                         }
9965                 );
9966                 assert_eq!(disconnect_event.is_some(), should_disconnect);
9967         };
9968
9969         // Fires timer ticks ensuring we only attempt to disconnect peers after reaching
9970         // `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
9971         let check_disconnect = |node: &Node| {
9972                 // No disconnect without any timer ticks.
9973                 check_disconnect_event(node, false);
9974
9975                 // No disconnect with 1 timer tick less than required.
9976                 for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS - 1 {
9977                         node.node.timer_tick_occurred();
9978                         check_disconnect_event(node, false);
9979                 }
9980
9981                 // Disconnect after reaching the required ticks.
9982                 node.node.timer_tick_occurred();
9983                 check_disconnect_event(node, true);
9984
9985                 // Disconnect again on the next tick if the peer hasn't been disconnected yet.
9986                 node.node.timer_tick_occurred();
9987                 check_disconnect_event(node, true);
9988         };
9989
9990         create_chan_between_nodes(&nodes[0], &nodes[1]);
9991
9992         // We'll start by performing a fee update with Alice (nodes[0]) on the channel.
9993         *nodes[0].fee_estimator.sat_per_kw.lock().unwrap() *= 2;
9994         nodes[0].node.timer_tick_occurred();
9995         check_added_monitors!(&nodes[0], 1);
9996         let alice_fee_update = get_htlc_update_msgs(&nodes[0], &nodes[1].node.get_our_node_id());
9997         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), alice_fee_update.update_fee.as_ref().unwrap());
9998         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &alice_fee_update.commitment_signed);
9999         check_added_monitors!(&nodes[1], 1);
10000
10001         // This will prompt Bob (nodes[1]) to respond with his `CommitmentSigned` and `RevokeAndACK`.
10002         let (bob_revoke_and_ack, bob_commitment_signed) = get_revoke_commit_msgs!(&nodes[1], nodes[0].node.get_our_node_id());
10003         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revoke_and_ack);
10004         check_added_monitors!(&nodes[0], 1);
10005         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_commitment_signed);
10006         check_added_monitors(&nodes[0], 1);
10007
10008         // Alice then needs to send her final `RevokeAndACK` to complete the commitment dance. We
10009         // pretend Bob hasn't received the message and check whether he'll disconnect Alice after
10010         // reaching `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10011         let alice_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
10012         check_disconnect(&nodes[1]);
10013
10014         // Now, we'll reconnect them to test awaiting a `ChannelReestablish` message.
10015         //
10016         // Note that since the commitment dance didn't complete above, Alice is expected to resend her
10017         // final `RevokeAndACK` to Bob to complete it.
10018         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
10019         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
10020         let bob_init = msgs::Init {
10021                 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
10022         };
10023         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &bob_init, true).unwrap();
10024         let alice_init = msgs::Init {
10025                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
10026         };
10027         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &alice_init, true).unwrap();
10028
10029         // Upon reconnection, Alice sends her `ChannelReestablish` to Bob. Alice, however, hasn't
10030         // received Bob's yet, so she should disconnect him after reaching
10031         // `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10032         let alice_channel_reestablish = get_event_msg!(
10033                 nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id()
10034         );
10035         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &alice_channel_reestablish);
10036         check_disconnect(&nodes[0]);
10037
10038         // Bob now sends his `ChannelReestablish` to Alice to resume the channel and consider it "live".
10039         let bob_channel_reestablish = nodes[1].node.get_and_clear_pending_msg_events().iter().find_map(|event|
10040                 if let MessageSendEvent::SendChannelReestablish { node_id, msg } = event {
10041                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
10042                         Some(msg.clone())
10043                 } else {
10044                         None
10045                 }
10046         ).unwrap();
10047         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bob_channel_reestablish);
10048
10049         // Sanity check that Alice won't disconnect Bob since she's no longer waiting for any messages.
10050         for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS {
10051                 nodes[0].node.timer_tick_occurred();
10052                 check_disconnect_event(&nodes[0], false);
10053         }
10054
10055         // However, Bob is still waiting on Alice's `RevokeAndACK`, so he should disconnect her after
10056         // reaching `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10057         check_disconnect(&nodes[1]);
10058
10059         // Finally, have Bob process the last message.
10060         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &alice_revoke_and_ack);
10061         check_added_monitors(&nodes[1], 1);
10062
10063         // At this point, neither node should attempt to disconnect each other, since they aren't
10064         // waiting on any messages.
10065         for node in &nodes {
10066                 for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS {
10067                         node.node.timer_tick_occurred();
10068                         check_disconnect_event(node, false);
10069                 }
10070         }
10071 }
10072
10073 #[test]
10074 fn test_remove_expired_outbound_unfunded_channels() {
10075         let chanmon_cfgs = create_chanmon_cfgs(2);
10076         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10077         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10078         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10079
10080         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
10081         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10082         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
10083         let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10084         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
10085
10086         let events = nodes[0].node.get_and_clear_pending_events();
10087         assert_eq!(events.len(), 1);
10088         match events[0] {
10089                 Event::FundingGenerationReady { .. } => (),
10090                 _ => panic!("Unexpected event"),
10091         };
10092
10093         // Asserts the outbound channel has been removed from a nodes[0]'s peer state map.
10094         let check_outbound_channel_existence = |should_exist: bool| {
10095                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
10096                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
10097                 assert_eq!(chan_lock.outbound_v1_channel_by_id.contains_key(&temp_channel_id), should_exist);
10098         };
10099
10100         // Channel should exist without any timer ticks.
10101         check_outbound_channel_existence(true);
10102
10103         // Channel should exist with 1 timer tick less than required.
10104         for _ in 0..UNFUNDED_CHANNEL_AGE_LIMIT_TICKS - 1 {
10105                 nodes[0].node.timer_tick_occurred();
10106                 check_outbound_channel_existence(true)
10107         }
10108
10109         // Remove channel after reaching the required ticks.
10110         nodes[0].node.timer_tick_occurred();
10111         check_outbound_channel_existence(false);
10112
10113         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
10114         assert_eq!(msg_events.len(), 1);
10115         match msg_events[0] {
10116                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
10117                         assert_eq!(msg.data, "Force-closing pending channel due to timeout awaiting establishment handshake");
10118                 },
10119                 _ => panic!("Unexpected event"),
10120         }
10121         check_closed_event(&nodes[0], 1, ClosureReason::HolderForceClosed, false, &[nodes[1].node.get_our_node_id()], 100000);
10122 }
10123
10124 #[test]
10125 fn test_remove_expired_inbound_unfunded_channels() {
10126         let chanmon_cfgs = create_chanmon_cfgs(2);
10127         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10128         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10129         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10130
10131         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
10132         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10133         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
10134         let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10135         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
10136
10137         let events = nodes[0].node.get_and_clear_pending_events();
10138         assert_eq!(events.len(), 1);
10139         match events[0] {
10140                 Event::FundingGenerationReady { .. } => (),
10141                 _ => panic!("Unexpected event"),
10142         };
10143
10144         // Asserts the inbound channel has been removed from a nodes[1]'s peer state map.
10145         let check_inbound_channel_existence = |should_exist: bool| {
10146                 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
10147                 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
10148                 assert_eq!(chan_lock.inbound_v1_channel_by_id.contains_key(&temp_channel_id), should_exist);
10149         };
10150
10151         // Channel should exist without any timer ticks.
10152         check_inbound_channel_existence(true);
10153
10154         // Channel should exist with 1 timer tick less than required.
10155         for _ in 0..UNFUNDED_CHANNEL_AGE_LIMIT_TICKS - 1 {
10156                 nodes[1].node.timer_tick_occurred();
10157                 check_inbound_channel_existence(true)
10158         }
10159
10160         // Remove channel after reaching the required ticks.
10161         nodes[1].node.timer_tick_occurred();
10162         check_inbound_channel_existence(false);
10163
10164         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
10165         assert_eq!(msg_events.len(), 1);
10166         match msg_events[0] {
10167                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
10168                         assert_eq!(msg.data, "Force-closing pending channel due to timeout awaiting establishment handshake");
10169                 },
10170                 _ => panic!("Unexpected event"),
10171         }
10172         check_closed_event(&nodes[1], 1, ClosureReason::HolderForceClosed, false, &[nodes[0].node.get_our_node_id()], 100000);
10173 }
10174
10175 fn do_test_multi_post_event_actions(do_reload: bool) {
10176         // Tests handling multiple post-Event actions at once.
10177         // There is specific code in ChannelManager to handle channels where multiple post-Event
10178         // `ChannelMonitorUpdates` are pending at once. This test exercises that code.
10179         //
10180         // Specifically, we test calling `get_and_clear_pending_events` while there are two
10181         // PaymentSents from different channels and one channel has two pending `ChannelMonitorUpdate`s
10182         // - one from an RAA and one from an inbound commitment_signed.
10183         let chanmon_cfgs = create_chanmon_cfgs(3);
10184         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
10185         let (persister, chain_monitor);
10186         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
10187         let nodes_0_deserialized;
10188         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
10189
10190         let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
10191         let chan_id_2 = create_announced_chan_between_nodes(&nodes, 0, 2).2;
10192
10193         send_payment(&nodes[0], &[&nodes[1]], 1_000_000);
10194         send_payment(&nodes[0], &[&nodes[2]], 1_000_000);
10195
10196         let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
10197         let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[2]], 1_000_000);
10198
10199         nodes[1].node.claim_funds(our_payment_preimage);
10200         check_added_monitors!(nodes[1], 1);
10201         expect_payment_claimed!(nodes[1], our_payment_hash, 1_000_000);
10202
10203         nodes[2].node.claim_funds(payment_preimage_2);
10204         check_added_monitors!(nodes[2], 1);
10205         expect_payment_claimed!(nodes[2], payment_hash_2, 1_000_000);
10206
10207         for dest in &[1, 2] {
10208                 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[*dest], nodes[0].node.get_our_node_id());
10209                 nodes[0].node.handle_update_fulfill_htlc(&nodes[*dest].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
10210                 commitment_signed_dance!(nodes[0], nodes[*dest], htlc_fulfill_updates.commitment_signed, false);
10211                 check_added_monitors(&nodes[0], 0);
10212         }
10213
10214         let (route, payment_hash_3, _, payment_secret_3) =
10215                 get_route_and_payment_hash!(nodes[1], nodes[0], 100_000);
10216         let payment_id = PaymentId(payment_hash_3.0);
10217         nodes[1].node.send_payment_with_route(&route, payment_hash_3,
10218                 RecipientOnionFields::secret_only(payment_secret_3), payment_id).unwrap();
10219         check_added_monitors(&nodes[1], 1);
10220
10221         let send_event = SendEvent::from_node(&nodes[1]);
10222         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_event.msgs[0]);
10223         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_event.commitment_msg);
10224         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
10225
10226         if do_reload {
10227                 let nodes_0_serialized = nodes[0].node.encode();
10228                 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
10229                 let chan_1_monitor_serialized = get_monitor!(nodes[0], chan_id_2).encode();
10230                 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);
10231
10232                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
10233                 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id());
10234
10235                 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
10236                 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[2]));
10237         }
10238
10239         let events = nodes[0].node.get_and_clear_pending_events();
10240         assert_eq!(events.len(), 4);
10241         if let Event::PaymentSent { payment_preimage, .. } = events[0] {
10242                 assert!(payment_preimage == our_payment_preimage || payment_preimage == payment_preimage_2);
10243         } else { panic!(); }
10244         if let Event::PaymentSent { payment_preimage, .. } = events[1] {
10245                 assert!(payment_preimage == our_payment_preimage || payment_preimage == payment_preimage_2);
10246         } else { panic!(); }
10247         if let Event::PaymentPathSuccessful { .. } = events[2] {} else { panic!(); }
10248         if let Event::PaymentPathSuccessful { .. } = events[3] {} else { panic!(); }
10249
10250         // After the events are processed, the ChannelMonitorUpdates will be released and, upon their
10251         // completion, we'll respond to nodes[1] with an RAA + CS.
10252         get_revoke_commit_msgs(&nodes[0], &nodes[1].node.get_our_node_id());
10253         check_added_monitors(&nodes[0], 3);
10254 }
10255
10256 #[test]
10257 fn test_multi_post_event_actions() {
10258         do_test_multi_post_event_actions(true);
10259         do_test_multi_post_event_actions(false);
10260 }