]> git.bitcoin.ninja Git - rust-lightning/blob - lightning/src/ln/functional_tests.rs
Add duplicate temporary_channel_id for 2 peers test
[rust-lightning] / lightning / src / ln / functional_tests.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
8 // licenses.
9
10 //! Tests that test standing up a network of ChannelManagers, creating channels, sending
11 //! payments/messages between them, and often checking the resulting ChannelMonitors are able to
12 //! claim outputs on-chain.
13
14 use crate::chain;
15 use crate::chain::{ChannelMonitorUpdateStatus, Confirm, Listen, Watch};
16 use crate::chain::chaininterface::LowerBoundedFeeEstimator;
17 use crate::chain::channelmonitor;
18 use crate::chain::channelmonitor::{CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY};
19 use crate::chain::transaction::OutPoint;
20 use crate::chain::keysinterface::{BaseSign, EntropySource, KeysInterface};
21 use crate::ln::{PaymentPreimage, PaymentSecret, PaymentHash};
22 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};
23 use crate::ln::channelmanager::{self, PaymentId, RAACommitmentOrder, PaymentSendFailure, BREAKDOWN_TIMEOUT, MIN_CLTV_EXPIRY_DELTA};
24 use crate::ln::channel::{Channel, ChannelError};
25 use crate::ln::{chan_utils, onion_utils};
26 use crate::ln::chan_utils::{OFFERED_HTLC_SCRIPT_WEIGHT, htlc_success_tx_weight, htlc_timeout_tx_weight, HTLCOutputInCommitment};
27 use crate::routing::gossip::{NetworkGraph, NetworkUpdate};
28 use crate::routing::router::{PaymentParameters, Route, RouteHop, RouteParameters, find_route, get_route};
29 use crate::ln::features::{ChannelFeatures, NodeFeatures};
30 use crate::ln::msgs;
31 use crate::ln::msgs::{ChannelMessageHandler, RoutingMessageHandler, ErrorAction};
32 use crate::util::enforcing_trait_impls::EnforcingSigner;
33 use crate::util::test_utils;
34 use crate::util::events::{Event, MessageSendEvent, MessageSendEventsProvider, PaymentPurpose, ClosureReason, HTLCDestination};
35 use crate::util::errors::APIError;
36 use crate::util::ser::{Writeable, ReadableArgs};
37 use crate::util::config::UserConfig;
38
39 use bitcoin::hash_types::BlockHash;
40 use bitcoin::blockdata::block::{Block, BlockHeader};
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, TxMerkleNode, 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};
60
61 use crate::ln::functional_test_utils::*;
62 use crate::ln::chan_utils::CommitmentTransaction;
63
64 #[test]
65 fn test_insane_channel_opens() {
66         // Stand up a network of 2 nodes
67         use crate::ln::channel::TOTAL_BITCOIN_SUPPLY_SATOSHIS;
68         let mut cfg = UserConfig::default();
69         cfg.channel_handshake_limits.max_funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1;
70         let chanmon_cfgs = create_chanmon_cfgs(2);
71         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
72         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(cfg)]);
73         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
74
75         // Instantiate channel parameters where we push the maximum msats given our
76         // funding satoshis
77         let channel_value_sat = 31337; // same as funding satoshis
78         let channel_reserve_satoshis = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value_sat, &cfg);
79         let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
80
81         // Have node0 initiate a channel to node1 with aforementioned parameters
82         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
83
84         // Extract the channel open message from node0 to node1
85         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
86
87         // Test helper that asserts we get the correct error string given a mutator
88         // that supposedly makes the channel open message insane
89         let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
90                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &message_mutator(open_channel_message.clone()));
91                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
92                 assert_eq!(msg_events.len(), 1);
93                 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
94                 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
95                         match action {
96                                 &ErrorAction::SendErrorMessage { .. } => {
97                                         nodes[1].logger.assert_log_regex("lightning::ln::channelmanager".to_string(), expected_regex, 1);
98                                 },
99                                 _ => panic!("unexpected event!"),
100                         }
101                 } else { assert!(false); }
102         };
103
104         use crate::ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
105
106         // Test all mutations that would make the channel open message insane
107         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 });
108         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 });
109
110         insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
111
112         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 });
113
114         insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
115
116         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 });
117
118         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 });
119
120         insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
121
122         insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
123 }
124
125 #[test]
126 fn test_funding_exceeds_no_wumbo_limit() {
127         // Test that if a peer does not support wumbo channels, we'll refuse to open a wumbo channel to
128         // them.
129         use crate::ln::channel::MAX_FUNDING_SATOSHIS_NO_WUMBO;
130         let chanmon_cfgs = create_chanmon_cfgs(2);
131         let mut node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
132         node_cfgs[1].features = channelmanager::provided_init_features().clear_wumbo();
133         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
134         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
135
136         match nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), MAX_FUNDING_SATOSHIS_NO_WUMBO + 1, 0, 42, None) {
137                 Err(APIError::APIMisuseError { err }) => {
138                         assert_eq!(format!("funding_value must not exceed {}, it was {}", MAX_FUNDING_SATOSHIS_NO_WUMBO, MAX_FUNDING_SATOSHIS_NO_WUMBO + 1), err);
139                 },
140                 _ => panic!()
141         }
142 }
143
144 fn do_test_counterparty_no_reserve(send_from_initiator: bool) {
145         // A peer providing a channel_reserve_satoshis of 0 (or less than our dust limit) is insecure,
146         // but only for them. Because some LSPs do it with some level of trust of the clients (for a
147         // substantial UX improvement), we explicitly allow it. Because it's unlikely to happen often
148         // in normal testing, we test it explicitly here.
149         let chanmon_cfgs = create_chanmon_cfgs(2);
150         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
151         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
152         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
153         let default_config = UserConfig::default();
154
155         // Have node0 initiate a channel to node1 with aforementioned parameters
156         let mut push_amt = 100_000_000;
157         let feerate_per_kw = 253;
158         let opt_anchors = false;
159         push_amt -= feerate_per_kw as u64 * (commitment_tx_base_weight(opt_anchors) + 4 * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000 * 1000;
160         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
161
162         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();
163         let mut open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
164         if !send_from_initiator {
165                 open_channel_message.channel_reserve_satoshis = 0;
166                 open_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
167         }
168         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_channel_message);
169
170         // Extract the channel accept message from node1 to node0
171         let mut accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
172         if send_from_initiator {
173                 accept_channel_message.channel_reserve_satoshis = 0;
174                 accept_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
175         }
176         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_channel_message);
177         {
178                 let sender_node = if send_from_initiator { &nodes[1] } else { &nodes[0] };
179                 let counterparty_node = if send_from_initiator { &nodes[0] } else { &nodes[1] };
180                 let mut sender_node_per_peer_lock;
181                 let mut sender_node_peer_state_lock;
182                 let mut chan = get_channel_ref!(sender_node, counterparty_node, sender_node_per_peer_lock, sender_node_peer_state_lock, temp_channel_id);
183                 chan.holder_selected_channel_reserve_satoshis = 0;
184                 chan.holder_max_htlc_value_in_flight_msat = 100_000_000;
185         }
186
187         let funding_tx = sign_funding_transaction(&nodes[0], &nodes[1], 100_000, temp_channel_id);
188         let funding_msgs = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &funding_tx);
189         create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_msgs.0);
190
191         // nodes[0] should now be able to send the full balance to nodes[1], violating nodes[1]'s
192         // security model if it ever tries to send funds back to nodes[0] (but that's not our problem).
193         if send_from_initiator {
194                 send_payment(&nodes[0], &[&nodes[1]], 100_000_000
195                         // Note that for outbound channels we have to consider the commitment tx fee and the
196                         // "fee spike buffer", which is currently a multiple of the total commitment tx fee as
197                         // well as an additional HTLC.
198                         - FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE * commit_tx_fee_msat(feerate_per_kw, 2, opt_anchors));
199         } else {
200                 send_payment(&nodes[1], &[&nodes[0]], push_amt);
201         }
202 }
203
204 #[test]
205 fn test_counterparty_no_reserve() {
206         do_test_counterparty_no_reserve(true);
207         do_test_counterparty_no_reserve(false);
208 }
209
210 #[test]
211 fn test_async_inbound_update_fee() {
212         let chanmon_cfgs = create_chanmon_cfgs(2);
213         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
214         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
215         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
216         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
217
218         // balancing
219         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
220
221         // A                                        B
222         // update_fee                            ->
223         // send (1) commitment_signed            -.
224         //                                       <- update_add_htlc/commitment_signed
225         // send (2) RAA (awaiting remote revoke) -.
226         // (1) commitment_signed is delivered    ->
227         //                                       .- send (3) RAA (awaiting remote revoke)
228         // (2) RAA is delivered                  ->
229         //                                       .- send (4) commitment_signed
230         //                                       <- (3) RAA is delivered
231         // send (5) commitment_signed            -.
232         //                                       <- (4) commitment_signed is delivered
233         // send (6) RAA                          -.
234         // (5) commitment_signed is delivered    ->
235         //                                       <- RAA
236         // (6) RAA is delivered                  ->
237
238         // First nodes[0] generates an update_fee
239         {
240                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
241                 *feerate_lock += 20;
242         }
243         nodes[0].node.timer_tick_occurred();
244         check_added_monitors!(nodes[0], 1);
245
246         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
247         assert_eq!(events_0.len(), 1);
248         let (update_msg, commitment_signed) = match events_0[0] { // (1)
249                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
250                         (update_fee.as_ref(), commitment_signed)
251                 },
252                 _ => panic!("Unexpected event"),
253         };
254
255         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
256
257         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
258         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
259         nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
260         check_added_monitors!(nodes[1], 1);
261
262         let payment_event = {
263                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
264                 assert_eq!(events_1.len(), 1);
265                 SendEvent::from_event(events_1.remove(0))
266         };
267         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
268         assert_eq!(payment_event.msgs.len(), 1);
269
270         // ...now when the messages get delivered everyone should be happy
271         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
272         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
273         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
274         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
275         check_added_monitors!(nodes[0], 1);
276
277         // deliver(1), generate (3):
278         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
279         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
280         // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
281         check_added_monitors!(nodes[1], 1);
282
283         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
284         let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
285         assert!(bs_update.update_add_htlcs.is_empty()); // (4)
286         assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
287         assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
288         assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
289         assert!(bs_update.update_fee.is_none()); // (4)
290         check_added_monitors!(nodes[1], 1);
291
292         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
293         let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
294         assert!(as_update.update_add_htlcs.is_empty()); // (5)
295         assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
296         assert!(as_update.update_fail_htlcs.is_empty()); // (5)
297         assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
298         assert!(as_update.update_fee.is_none()); // (5)
299         check_added_monitors!(nodes[0], 1);
300
301         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
302         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
303         // only (6) so get_event_msg's assert(len == 1) passes
304         check_added_monitors!(nodes[0], 1);
305
306         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
307         let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
308         check_added_monitors!(nodes[1], 1);
309
310         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
311         check_added_monitors!(nodes[0], 1);
312
313         let events_2 = nodes[0].node.get_and_clear_pending_events();
314         assert_eq!(events_2.len(), 1);
315         match events_2[0] {
316                 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
317                 _ => panic!("Unexpected event"),
318         }
319
320         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
321         check_added_monitors!(nodes[1], 1);
322 }
323
324 #[test]
325 fn test_update_fee_unordered_raa() {
326         // Just the intro to the previous test followed by an out-of-order RAA (which caused a
327         // crash in an earlier version of the update_fee patch)
328         let chanmon_cfgs = create_chanmon_cfgs(2);
329         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
330         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
331         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
332         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
333
334         // balancing
335         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
336
337         // First nodes[0] generates an update_fee
338         {
339                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
340                 *feerate_lock += 20;
341         }
342         nodes[0].node.timer_tick_occurred();
343         check_added_monitors!(nodes[0], 1);
344
345         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
346         assert_eq!(events_0.len(), 1);
347         let update_msg = match events_0[0] { // (1)
348                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
349                         update_fee.as_ref()
350                 },
351                 _ => panic!("Unexpected event"),
352         };
353
354         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
355
356         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
357         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
358         nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
359         check_added_monitors!(nodes[1], 1);
360
361         let payment_event = {
362                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
363                 assert_eq!(events_1.len(), 1);
364                 SendEvent::from_event(events_1.remove(0))
365         };
366         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
367         assert_eq!(payment_event.msgs.len(), 1);
368
369         // ...now when the messages get delivered everyone should be happy
370         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
371         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
372         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
373         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
374         check_added_monitors!(nodes[0], 1);
375
376         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
377         check_added_monitors!(nodes[1], 1);
378
379         // We can't continue, sadly, because our (1) now has a bogus signature
380 }
381
382 #[test]
383 fn test_multi_flight_update_fee() {
384         let chanmon_cfgs = create_chanmon_cfgs(2);
385         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
386         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
387         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
388         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
389
390         // A                                        B
391         // update_fee/commitment_signed          ->
392         //                                       .- send (1) RAA and (2) commitment_signed
393         // update_fee (never committed)          ->
394         // (3) update_fee                        ->
395         // We have to manually generate the above update_fee, it is allowed by the protocol but we
396         // don't track which updates correspond to which revoke_and_ack responses so we're in
397         // AwaitingRAA mode and will not generate the update_fee yet.
398         //                                       <- (1) RAA delivered
399         // (3) is generated and send (4) CS      -.
400         // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
401         // know the per_commitment_point to use for it.
402         //                                       <- (2) commitment_signed delivered
403         // revoke_and_ack                        ->
404         //                                          B should send no response here
405         // (4) commitment_signed delivered       ->
406         //                                       <- RAA/commitment_signed delivered
407         // revoke_and_ack                        ->
408
409         // First nodes[0] generates an update_fee
410         let initial_feerate;
411         {
412                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
413                 initial_feerate = *feerate_lock;
414                 *feerate_lock = initial_feerate + 20;
415         }
416         nodes[0].node.timer_tick_occurred();
417         check_added_monitors!(nodes[0], 1);
418
419         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
420         assert_eq!(events_0.len(), 1);
421         let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
422                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
423                         (update_fee.as_ref().unwrap(), commitment_signed)
424                 },
425                 _ => panic!("Unexpected event"),
426         };
427
428         // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
429         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
430         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
431         let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
432         check_added_monitors!(nodes[1], 1);
433
434         // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
435         // transaction:
436         {
437                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
438                 *feerate_lock = initial_feerate + 40;
439         }
440         nodes[0].node.timer_tick_occurred();
441         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
442         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
443
444         // Create the (3) update_fee message that nodes[0] will generate before it does...
445         let mut update_msg_2 = msgs::UpdateFee {
446                 channel_id: update_msg_1.channel_id.clone(),
447                 feerate_per_kw: (initial_feerate + 30) as u32,
448         };
449
450         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
451
452         update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
453         // Deliver (3)
454         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
455
456         // Deliver (1), generating (3) and (4)
457         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
458         let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
459         check_added_monitors!(nodes[0], 1);
460         assert!(as_second_update.update_add_htlcs.is_empty());
461         assert!(as_second_update.update_fulfill_htlcs.is_empty());
462         assert!(as_second_update.update_fail_htlcs.is_empty());
463         assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
464         // Check that the update_fee newly generated matches what we delivered:
465         assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
466         assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
467
468         // Deliver (2) commitment_signed
469         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
470         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
471         check_added_monitors!(nodes[0], 1);
472         // No commitment_signed so get_event_msg's assert(len == 1) passes
473
474         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
475         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
476         check_added_monitors!(nodes[1], 1);
477
478         // Delever (4)
479         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
480         let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
481         check_added_monitors!(nodes[1], 1);
482
483         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
484         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
485         check_added_monitors!(nodes[0], 1);
486
487         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
488         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
489         // No commitment_signed so get_event_msg's assert(len == 1) passes
490         check_added_monitors!(nodes[0], 1);
491
492         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
493         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
494         check_added_monitors!(nodes[1], 1);
495 }
496
497 fn do_test_sanity_on_in_flight_opens(steps: u8) {
498         // Previously, we had issues deserializing channels when we hadn't connected the first block
499         // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
500         // serialization round-trips and simply do steps towards opening a channel and then drop the
501         // Node objects.
502
503         let chanmon_cfgs = create_chanmon_cfgs(2);
504         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
505         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
506         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
507
508         if steps & 0b1000_0000 != 0{
509                 let block = Block {
510                         header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
511                         txdata: vec![],
512                 };
513                 connect_block(&nodes[0], &block);
514                 connect_block(&nodes[1], &block);
515         }
516
517         if steps & 0x0f == 0 { return; }
518         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
519         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
520
521         if steps & 0x0f == 1 { return; }
522         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_channel);
523         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
524
525         if steps & 0x0f == 2 { return; }
526         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_channel);
527
528         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
529
530         if steps & 0x0f == 3 { return; }
531         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
532         check_added_monitors!(nodes[0], 0);
533         let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
534
535         if steps & 0x0f == 4 { return; }
536         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
537         {
538                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
539                 assert_eq!(added_monitors.len(), 1);
540                 assert_eq!(added_monitors[0].0, funding_output);
541                 added_monitors.clear();
542         }
543         let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
544
545         if steps & 0x0f == 5 { return; }
546         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
547         {
548                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
549                 assert_eq!(added_monitors.len(), 1);
550                 assert_eq!(added_monitors[0].0, funding_output);
551                 added_monitors.clear();
552         }
553
554         let events_4 = nodes[0].node.get_and_clear_pending_events();
555         assert_eq!(events_4.len(), 0);
556
557         if steps & 0x0f == 6 { return; }
558         create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
559
560         if steps & 0x0f == 7 { return; }
561         confirm_transaction_at(&nodes[0], &tx, 2);
562         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
563         create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
564         expect_channel_ready_event(&nodes[0], &nodes[1].node.get_our_node_id());
565 }
566
567 #[test]
568 fn test_sanity_on_in_flight_opens() {
569         do_test_sanity_on_in_flight_opens(0);
570         do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
571         do_test_sanity_on_in_flight_opens(1);
572         do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
573         do_test_sanity_on_in_flight_opens(2);
574         do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
575         do_test_sanity_on_in_flight_opens(3);
576         do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
577         do_test_sanity_on_in_flight_opens(4);
578         do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
579         do_test_sanity_on_in_flight_opens(5);
580         do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
581         do_test_sanity_on_in_flight_opens(6);
582         do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
583         do_test_sanity_on_in_flight_opens(7);
584         do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
585         do_test_sanity_on_in_flight_opens(8);
586         do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
587 }
588
589 #[test]
590 fn test_update_fee_vanilla() {
591         let chanmon_cfgs = create_chanmon_cfgs(2);
592         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
593         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
594         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
595         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
596
597         {
598                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
599                 *feerate_lock += 25;
600         }
601         nodes[0].node.timer_tick_occurred();
602         check_added_monitors!(nodes[0], 1);
603
604         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
605         assert_eq!(events_0.len(), 1);
606         let (update_msg, commitment_signed) = match events_0[0] {
607                         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 } } => {
608                         (update_fee.as_ref(), commitment_signed)
609                 },
610                 _ => panic!("Unexpected event"),
611         };
612         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
613
614         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
615         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
616         check_added_monitors!(nodes[1], 1);
617
618         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
619         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
620         check_added_monitors!(nodes[0], 1);
621
622         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
623         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
624         // No commitment_signed so get_event_msg's assert(len == 1) passes
625         check_added_monitors!(nodes[0], 1);
626
627         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
628         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
629         check_added_monitors!(nodes[1], 1);
630 }
631
632 #[test]
633 fn test_update_fee_that_funder_cannot_afford() {
634         let chanmon_cfgs = create_chanmon_cfgs(2);
635         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
636         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
637         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
638         let channel_value = 5000;
639         let push_sats = 700;
640         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, push_sats * 1000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
641         let channel_id = chan.2;
642         let secp_ctx = Secp256k1::new();
643         let default_config = UserConfig::default();
644         let bs_channel_reserve_sats = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value, &default_config);
645
646         let opt_anchors = false;
647
648         // Calculate the maximum feerate that A can afford. Note that we don't send an update_fee
649         // CONCURRENT_INBOUND_HTLC_FEE_BUFFER HTLCs before actually running out of local balance, so we
650         // calculate two different feerates here - the expected local limit as well as the expected
651         // remote limit.
652         let feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / (commitment_tx_base_weight(opt_anchors) + CONCURRENT_INBOUND_HTLC_FEE_BUFFER as u64 * COMMITMENT_TX_WEIGHT_PER_HTLC)) as u32;
653         let non_buffer_feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / commitment_tx_base_weight(opt_anchors)) as u32;
654         {
655                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
656                 *feerate_lock = feerate;
657         }
658         nodes[0].node.timer_tick_occurred();
659         check_added_monitors!(nodes[0], 1);
660         let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
661
662         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
663
664         commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
665
666         // Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate set above.
667         {
668                 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
669
670                 //We made sure neither party's funds are below the dust limit and there are no HTLCs here
671                 assert_eq!(commitment_tx.output.len(), 2);
672                 let total_fee: u64 = commit_tx_fee_msat(feerate, 0, opt_anchors) / 1000;
673                 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
674                 actual_fee = channel_value - actual_fee;
675                 assert_eq!(total_fee, actual_fee);
676         }
677
678         {
679                 // Increment the feerate by a small constant, accounting for rounding errors
680                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
681                 *feerate_lock += 4;
682         }
683         nodes[0].node.timer_tick_occurred();
684         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot afford to send new feerate at {}", feerate + 4), 1);
685         check_added_monitors!(nodes[0], 0);
686
687         const INITIAL_COMMITMENT_NUMBER: u64 = 281474976710654;
688
689         // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
690         // needed to sign the new commitment tx and (2) sign the new commitment tx.
691         let (local_revocation_basepoint, local_htlc_basepoint, local_funding) = {
692                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
693                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
694                 let local_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
695                 let chan_signer = local_chan.get_signer();
696                 let pubkeys = chan_signer.pubkeys();
697                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
698                  pubkeys.funding_pubkey)
699         };
700         let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point, remote_funding) = {
701                 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
702                 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
703                 let remote_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
704                 let chan_signer = remote_chan.get_signer();
705                 let pubkeys = chan_signer.pubkeys();
706                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
707                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
708                  pubkeys.funding_pubkey)
709         };
710
711         // Assemble the set of keys we can use for signatures for our commitment_signed message.
712         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
713                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
714
715         let res = {
716                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
717                 let local_chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
718                 let local_chan = local_chan_lock.channel_by_id.get(&chan.2).unwrap();
719                 let local_chan_signer = local_chan.get_signer();
720                 let mut htlcs: Vec<(HTLCOutputInCommitment, ())> = vec![];
721                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
722                         INITIAL_COMMITMENT_NUMBER - 1,
723                         push_sats,
724                         channel_value - push_sats - commit_tx_fee_msat(non_buffer_feerate + 4, 0, opt_anchors) / 1000,
725                         opt_anchors, local_funding, remote_funding,
726                         commit_tx_keys.clone(),
727                         non_buffer_feerate + 4,
728                         &mut htlcs,
729                         &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
730                 );
731                 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
732         };
733
734         let commit_signed_msg = msgs::CommitmentSigned {
735                 channel_id: chan.2,
736                 signature: res.0,
737                 htlc_signatures: res.1
738         };
739
740         let update_fee = msgs::UpdateFee {
741                 channel_id: chan.2,
742                 feerate_per_kw: non_buffer_feerate + 4,
743         };
744
745         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_fee);
746
747         //While producing the commitment_signed response after handling a received update_fee request the
748         //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
749         //Should produce and error.
750         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
751         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
752         check_added_monitors!(nodes[1], 1);
753         check_closed_broadcast!(nodes[1], true);
754         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: String::from("Funding remote cannot afford proposed new fee") });
755 }
756
757 #[test]
758 fn test_update_fee_with_fundee_update_add_htlc() {
759         let chanmon_cfgs = create_chanmon_cfgs(2);
760         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
761         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
762         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
763         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
764
765         // balancing
766         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
767
768         {
769                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
770                 *feerate_lock += 20;
771         }
772         nodes[0].node.timer_tick_occurred();
773         check_added_monitors!(nodes[0], 1);
774
775         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
776         assert_eq!(events_0.len(), 1);
777         let (update_msg, commitment_signed) = match events_0[0] {
778                         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 } } => {
779                         (update_fee.as_ref(), commitment_signed)
780                 },
781                 _ => panic!("Unexpected event"),
782         };
783         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
784         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
785         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
786         check_added_monitors!(nodes[1], 1);
787
788         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 800000);
789
790         // nothing happens since node[1] is in AwaitingRemoteRevoke
791         nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
792         {
793                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
794                 assert_eq!(added_monitors.len(), 0);
795                 added_monitors.clear();
796         }
797         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
798         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
799         // node[1] has nothing to do
800
801         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
802         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
803         check_added_monitors!(nodes[0], 1);
804
805         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
806         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
807         // No commitment_signed so get_event_msg's assert(len == 1) passes
808         check_added_monitors!(nodes[0], 1);
809         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
810         check_added_monitors!(nodes[1], 1);
811         // AwaitingRemoteRevoke ends here
812
813         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
814         assert_eq!(commitment_update.update_add_htlcs.len(), 1);
815         assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
816         assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
817         assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
818         assert_eq!(commitment_update.update_fee.is_none(), true);
819
820         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
821         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
822         check_added_monitors!(nodes[0], 1);
823         let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
824
825         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
826         check_added_monitors!(nodes[1], 1);
827         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
828
829         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
830         check_added_monitors!(nodes[1], 1);
831         let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
832         // No commitment_signed so get_event_msg's assert(len == 1) passes
833
834         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
835         check_added_monitors!(nodes[0], 1);
836         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
837
838         expect_pending_htlcs_forwardable!(nodes[0]);
839
840         let events = nodes[0].node.get_and_clear_pending_events();
841         assert_eq!(events.len(), 1);
842         match events[0] {
843                 Event::PaymentClaimable { .. } => { },
844                 _ => panic!("Unexpected event"),
845         };
846
847         claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
848
849         send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
850         send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
851         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
852         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
853         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
854 }
855
856 #[test]
857 fn test_update_fee() {
858         let chanmon_cfgs = create_chanmon_cfgs(2);
859         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
860         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
861         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
862         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
863         let channel_id = chan.2;
864
865         // A                                        B
866         // (1) update_fee/commitment_signed      ->
867         //                                       <- (2) revoke_and_ack
868         //                                       .- send (3) commitment_signed
869         // (4) update_fee/commitment_signed      ->
870         //                                       .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
871         //                                       <- (3) commitment_signed delivered
872         // send (6) revoke_and_ack               -.
873         //                                       <- (5) deliver revoke_and_ack
874         // (6) deliver revoke_and_ack            ->
875         //                                       .- send (7) commitment_signed in response to (4)
876         //                                       <- (7) deliver commitment_signed
877         // revoke_and_ack                        ->
878
879         // Create and deliver (1)...
880         let feerate;
881         {
882                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
883                 feerate = *feerate_lock;
884                 *feerate_lock = feerate + 20;
885         }
886         nodes[0].node.timer_tick_occurred();
887         check_added_monitors!(nodes[0], 1);
888
889         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
890         assert_eq!(events_0.len(), 1);
891         let (update_msg, commitment_signed) = match events_0[0] {
892                         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 } } => {
893                         (update_fee.as_ref(), commitment_signed)
894                 },
895                 _ => panic!("Unexpected event"),
896         };
897         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
898
899         // Generate (2) and (3):
900         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
901         let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
902         check_added_monitors!(nodes[1], 1);
903
904         // Deliver (2):
905         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
906         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
907         check_added_monitors!(nodes[0], 1);
908
909         // Create and deliver (4)...
910         {
911                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
912                 *feerate_lock = feerate + 30;
913         }
914         nodes[0].node.timer_tick_occurred();
915         check_added_monitors!(nodes[0], 1);
916         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
917         assert_eq!(events_0.len(), 1);
918         let (update_msg, commitment_signed) = match events_0[0] {
919                         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 } } => {
920                         (update_fee.as_ref(), commitment_signed)
921                 },
922                 _ => panic!("Unexpected event"),
923         };
924
925         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
926         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
927         check_added_monitors!(nodes[1], 1);
928         // ... creating (5)
929         let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
930         // No commitment_signed so get_event_msg's assert(len == 1) passes
931
932         // Handle (3), creating (6):
933         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
934         check_added_monitors!(nodes[0], 1);
935         let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
936         // No commitment_signed so get_event_msg's assert(len == 1) passes
937
938         // Deliver (5):
939         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
940         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
941         check_added_monitors!(nodes[0], 1);
942
943         // Deliver (6), creating (7):
944         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
945         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
946         assert!(commitment_update.update_add_htlcs.is_empty());
947         assert!(commitment_update.update_fulfill_htlcs.is_empty());
948         assert!(commitment_update.update_fail_htlcs.is_empty());
949         assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
950         assert!(commitment_update.update_fee.is_none());
951         check_added_monitors!(nodes[1], 1);
952
953         // Deliver (7)
954         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
955         check_added_monitors!(nodes[0], 1);
956         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
957         // No commitment_signed so get_event_msg's assert(len == 1) passes
958
959         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
960         check_added_monitors!(nodes[1], 1);
961         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
962
963         assert_eq!(get_feerate!(nodes[0], nodes[1], channel_id), feerate + 30);
964         assert_eq!(get_feerate!(nodes[1], nodes[0], channel_id), feerate + 30);
965         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
966         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
967         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
968 }
969
970 #[test]
971 fn fake_network_test() {
972         // Simple test which builds a network of ChannelManagers, connects them to each other, and
973         // tests that payments get routed and transactions broadcast in semi-reasonable ways.
974         let chanmon_cfgs = create_chanmon_cfgs(4);
975         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
976         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
977         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
978
979         // Create some initial channels
980         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
981         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
982         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
983
984         // Rebalance the network a bit by relaying one payment through all the channels...
985         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
986         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
987         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
988         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
989
990         // Send some more payments
991         send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
992         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
993         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
994
995         // Test failure packets
996         let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
997         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
998
999         // Add a new channel that skips 3
1000         let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1001
1002         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
1003         send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
1004         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1005         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1006         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1007         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1008         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1009
1010         // Do some rebalance loop payments, simultaneously
1011         let mut hops = Vec::with_capacity(3);
1012         hops.push(RouteHop {
1013                 pubkey: nodes[2].node.get_our_node_id(),
1014                 node_features: NodeFeatures::empty(),
1015                 short_channel_id: chan_2.0.contents.short_channel_id,
1016                 channel_features: ChannelFeatures::empty(),
1017                 fee_msat: 0,
1018                 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1019         });
1020         hops.push(RouteHop {
1021                 pubkey: nodes[3].node.get_our_node_id(),
1022                 node_features: NodeFeatures::empty(),
1023                 short_channel_id: chan_3.0.contents.short_channel_id,
1024                 channel_features: ChannelFeatures::empty(),
1025                 fee_msat: 0,
1026                 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1027         });
1028         hops.push(RouteHop {
1029                 pubkey: nodes[1].node.get_our_node_id(),
1030                 node_features: channelmanager::provided_node_features(),
1031                 short_channel_id: chan_4.0.contents.short_channel_id,
1032                 channel_features: channelmanager::provided_channel_features(),
1033                 fee_msat: 1000000,
1034                 cltv_expiry_delta: TEST_FINAL_CLTV,
1035         });
1036         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;
1037         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;
1038         let payment_preimage_1 = send_along_route(&nodes[1], Route { paths: vec![hops], payment_params: None }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1039
1040         let mut hops = Vec::with_capacity(3);
1041         hops.push(RouteHop {
1042                 pubkey: nodes[3].node.get_our_node_id(),
1043                 node_features: NodeFeatures::empty(),
1044                 short_channel_id: chan_4.0.contents.short_channel_id,
1045                 channel_features: ChannelFeatures::empty(),
1046                 fee_msat: 0,
1047                 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1048         });
1049         hops.push(RouteHop {
1050                 pubkey: nodes[2].node.get_our_node_id(),
1051                 node_features: NodeFeatures::empty(),
1052                 short_channel_id: chan_3.0.contents.short_channel_id,
1053                 channel_features: ChannelFeatures::empty(),
1054                 fee_msat: 0,
1055                 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1056         });
1057         hops.push(RouteHop {
1058                 pubkey: nodes[1].node.get_our_node_id(),
1059                 node_features: channelmanager::provided_node_features(),
1060                 short_channel_id: chan_2.0.contents.short_channel_id,
1061                 channel_features: channelmanager::provided_channel_features(),
1062                 fee_msat: 1000000,
1063                 cltv_expiry_delta: TEST_FINAL_CLTV,
1064         });
1065         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;
1066         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;
1067         let payment_hash_2 = send_along_route(&nodes[1], Route { paths: vec![hops], payment_params: None }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1068
1069         // Claim the rebalances...
1070         fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1071         claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1072
1073         // Close down the channels...
1074         close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1075         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
1076         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1077         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1078         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1079         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1080         close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1081         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1082         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1083         close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1084         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1085         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1086 }
1087
1088 #[test]
1089 fn holding_cell_htlc_counting() {
1090         // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1091         // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1092         // commitment dance rounds.
1093         let chanmon_cfgs = create_chanmon_cfgs(3);
1094         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1095         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1096         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1097         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1098         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1099
1100         let mut payments = Vec::new();
1101         for _ in 0..crate::ln::channel::OUR_MAX_HTLCS {
1102                 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1103                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
1104                 payments.push((payment_preimage, payment_hash));
1105         }
1106         check_added_monitors!(nodes[1], 1);
1107
1108         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1109         assert_eq!(events.len(), 1);
1110         let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1111         assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1112
1113         // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1114         // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1115         // another HTLC.
1116         let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1117         {
1118                 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1), PaymentId(payment_hash_1.0)), true, APIError::ChannelUnavailable { ref err },
1119                         assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1120                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1121                 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1122         }
1123
1124         // This should also be true if we try to forward a payment.
1125         let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1126         {
1127                 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
1128                 check_added_monitors!(nodes[0], 1);
1129         }
1130
1131         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1132         assert_eq!(events.len(), 1);
1133         let payment_event = SendEvent::from_event(events.pop().unwrap());
1134         assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1135
1136         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1137         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1138         // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1139         // fails), the second will process the resulting failure and fail the HTLC backward.
1140         expect_pending_htlcs_forwardable!(nodes[1]);
1141         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 }]);
1142         check_added_monitors!(nodes[1], 1);
1143
1144         let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1145         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1146         commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1147
1148         expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1149
1150         // Now forward all the pending HTLCs and claim them back
1151         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1152         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1153         check_added_monitors!(nodes[2], 1);
1154
1155         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1156         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1157         check_added_monitors!(nodes[1], 1);
1158         let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1159
1160         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1161         check_added_monitors!(nodes[1], 1);
1162         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1163
1164         for ref update in as_updates.update_add_htlcs.iter() {
1165                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1166         }
1167         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1168         check_added_monitors!(nodes[2], 1);
1169         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1170         check_added_monitors!(nodes[2], 1);
1171         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1172
1173         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1174         check_added_monitors!(nodes[1], 1);
1175         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1176         check_added_monitors!(nodes[1], 1);
1177         let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1178
1179         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1180         check_added_monitors!(nodes[2], 1);
1181
1182         expect_pending_htlcs_forwardable!(nodes[2]);
1183
1184         let events = nodes[2].node.get_and_clear_pending_events();
1185         assert_eq!(events.len(), payments.len());
1186         for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1187                 match event {
1188                         &Event::PaymentClaimable { ref payment_hash, .. } => {
1189                                 assert_eq!(*payment_hash, *hash);
1190                         },
1191                         _ => panic!("Unexpected event"),
1192                 };
1193         }
1194
1195         for (preimage, _) in payments.drain(..) {
1196                 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1197         }
1198
1199         send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1200 }
1201
1202 #[test]
1203 fn duplicate_htlc_test() {
1204         // Test that we accept duplicate payment_hash HTLCs across the network and that
1205         // claiming/failing them are all separate and don't affect each other
1206         let chanmon_cfgs = create_chanmon_cfgs(6);
1207         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1208         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1209         let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1210
1211         // Create some initial channels to route via 3 to 4/5 from 0/1/2
1212         create_announced_chan_between_nodes(&nodes, 0, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1213         create_announced_chan_between_nodes(&nodes, 1, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1214         create_announced_chan_between_nodes(&nodes, 2, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1215         create_announced_chan_between_nodes(&nodes, 3, 4, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1216         create_announced_chan_between_nodes(&nodes, 3, 5, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1217
1218         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1219
1220         *nodes[0].network_payment_count.borrow_mut() -= 1;
1221         assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1222
1223         *nodes[0].network_payment_count.borrow_mut() -= 1;
1224         assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1225
1226         claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1227         fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1228         claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1229 }
1230
1231 #[test]
1232 fn test_duplicate_htlc_different_direction_onchain() {
1233         // Test that ChannelMonitor doesn't generate 2 preimage txn
1234         // when we have 2 HTLCs with same preimage that go across a node
1235         // in opposite directions, even with the same payment secret.
1236         let chanmon_cfgs = create_chanmon_cfgs(2);
1237         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1238         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1239         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1240
1241         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1242
1243         // balancing
1244         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1245
1246         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1247
1248         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1249         let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200).unwrap();
1250         send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1251
1252         // Provide preimage to node 0 by claiming payment
1253         nodes[0].node.claim_funds(payment_preimage);
1254         expect_payment_claimed!(nodes[0], payment_hash, 800_000);
1255         check_added_monitors!(nodes[0], 1);
1256
1257         // Broadcast node 1 commitment txn
1258         let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1259
1260         assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1261         let mut has_both_htlcs = 0; // check htlcs match ones committed
1262         for outp in remote_txn[0].output.iter() {
1263                 if outp.value == 800_000 / 1000 {
1264                         has_both_htlcs += 1;
1265                 } else if outp.value == 900_000 / 1000 {
1266                         has_both_htlcs += 1;
1267                 }
1268         }
1269         assert_eq!(has_both_htlcs, 2);
1270
1271         mine_transaction(&nodes[0], &remote_txn[0]);
1272         check_added_monitors!(nodes[0], 1);
1273         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
1274         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
1275
1276         let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1277         assert_eq!(claim_txn.len(), 3);
1278
1279         check_spends!(claim_txn[0], remote_txn[0]); // Immediate HTLC claim with preimage
1280         check_spends!(claim_txn[1], remote_txn[0]);
1281         check_spends!(claim_txn[2], remote_txn[0]);
1282         let preimage_tx = &claim_txn[0];
1283         let (preimage_bump_tx, timeout_tx) = if claim_txn[1].input[0].previous_output == preimage_tx.input[0].previous_output {
1284                 (&claim_txn[1], &claim_txn[2])
1285         } else {
1286                 (&claim_txn[2], &claim_txn[1])
1287         };
1288
1289         assert_eq!(preimage_tx.input.len(), 1);
1290         assert_eq!(preimage_bump_tx.input.len(), 1);
1291
1292         assert_eq!(preimage_tx.input.len(), 1);
1293         assert_eq!(preimage_tx.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1294         assert_eq!(remote_txn[0].output[preimage_tx.input[0].previous_output.vout as usize].value, 800);
1295
1296         assert_eq!(timeout_tx.input.len(), 1);
1297         assert_eq!(timeout_tx.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1298         check_spends!(timeout_tx, remote_txn[0]);
1299         assert_eq!(remote_txn[0].output[timeout_tx.input[0].previous_output.vout as usize].value, 900);
1300
1301         let events = nodes[0].node.get_and_clear_pending_msg_events();
1302         assert_eq!(events.len(), 3);
1303         for e in events {
1304                 match e {
1305                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1306                         MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1307                                 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1308                                 assert_eq!(msg.data, "Channel closed because commitment or closing transaction was confirmed on chain.");
1309                         },
1310                         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, .. } } => {
1311                                 assert!(update_add_htlcs.is_empty());
1312                                 assert!(update_fail_htlcs.is_empty());
1313                                 assert_eq!(update_fulfill_htlcs.len(), 1);
1314                                 assert!(update_fail_malformed_htlcs.is_empty());
1315                                 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1316                         },
1317                         _ => panic!("Unexpected event"),
1318                 }
1319         }
1320 }
1321
1322 #[test]
1323 fn test_basic_channel_reserve() {
1324         let chanmon_cfgs = create_chanmon_cfgs(2);
1325         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1326         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1327         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1328         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1329
1330         let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1331         let channel_reserve = chan_stat.channel_reserve_msat;
1332
1333         // The 2* and +1 are for the fee spike reserve.
1334         let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], nodes[1], chan.2), 1 + 1, get_opt_anchors!(nodes[0], nodes[1], chan.2));
1335         let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1336         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send + 1);
1337         let err = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).err().unwrap();
1338         match err {
1339                 PaymentSendFailure::AllFailedResendSafe(ref fails) => {
1340                         match &fails[0] {
1341                                 &APIError::ChannelUnavailable{ref err} =>
1342                                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1343                                 _ => panic!("Unexpected error variant"),
1344                         }
1345                 },
1346                 _ => panic!("Unexpected error variant"),
1347         }
1348         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1349         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send value that would put our balance under counterparty-announced channel reserve value".to_string(), 1);
1350
1351         send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1352 }
1353
1354 #[test]
1355 fn test_fee_spike_violation_fails_htlc() {
1356         let chanmon_cfgs = create_chanmon_cfgs(2);
1357         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1358         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1359         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1360         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1361
1362         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3460001);
1363         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1364         let secp_ctx = Secp256k1::new();
1365         let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1366
1367         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1368
1369         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1370         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &Some(payment_secret), cur_height, &None).unwrap();
1371         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1372         let msg = msgs::UpdateAddHTLC {
1373                 channel_id: chan.2,
1374                 htlc_id: 0,
1375                 amount_msat: htlc_msat,
1376                 payment_hash: payment_hash,
1377                 cltv_expiry: htlc_cltv,
1378                 onion_routing_packet: onion_packet,
1379         };
1380
1381         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1382
1383         // Now manually create the commitment_signed message corresponding to the update_add
1384         // nodes[0] just sent. In the code for construction of this message, "local" refers
1385         // to the sender of the message, and "remote" refers to the receiver.
1386
1387         let feerate_per_kw = get_feerate!(nodes[0], nodes[1], chan.2);
1388
1389         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1390
1391         // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1392         // needed to sign the new commitment tx and (2) sign the new commitment tx.
1393         let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1394                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1395                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1396                 let local_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
1397                 let chan_signer = local_chan.get_signer();
1398                 // Make the signer believe we validated another commitment, so we can release the secret
1399                 chan_signer.get_enforcement_state().last_holder_commitment -= 1;
1400
1401                 let pubkeys = chan_signer.pubkeys();
1402                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1403                  chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1404                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1405                  chan_signer.pubkeys().funding_pubkey)
1406         };
1407         let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1408                 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
1409                 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
1410                 let remote_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
1411                 let chan_signer = remote_chan.get_signer();
1412                 let pubkeys = chan_signer.pubkeys();
1413                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1414                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1415                  chan_signer.pubkeys().funding_pubkey)
1416         };
1417
1418         // Assemble the set of keys we can use for signatures for our commitment_signed message.
1419         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1420                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
1421
1422         // Build the remote commitment transaction so we can sign it, and then later use the
1423         // signature for the commitment_signed message.
1424         let local_chan_balance = 1313;
1425
1426         let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1427                 offered: false,
1428                 amount_msat: 3460001,
1429                 cltv_expiry: htlc_cltv,
1430                 payment_hash,
1431                 transaction_output_index: Some(1),
1432         };
1433
1434         let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1435
1436         let res = {
1437                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1438                 let local_chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1439                 let local_chan = local_chan_lock.channel_by_id.get(&chan.2).unwrap();
1440                 let local_chan_signer = local_chan.get_signer();
1441                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1442                         commitment_number,
1443                         95000,
1444                         local_chan_balance,
1445                         local_chan.opt_anchors(), local_funding, remote_funding,
1446                         commit_tx_keys.clone(),
1447                         feerate_per_kw,
1448                         &mut vec![(accepted_htlc_info, ())],
1449                         &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1450                 );
1451                 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
1452         };
1453
1454         let commit_signed_msg = msgs::CommitmentSigned {
1455                 channel_id: chan.2,
1456                 signature: res.0,
1457                 htlc_signatures: res.1
1458         };
1459
1460         // Send the commitment_signed message to the nodes[1].
1461         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1462         let _ = nodes[1].node.get_and_clear_pending_msg_events();
1463
1464         // Send the RAA to nodes[1].
1465         let raa_msg = msgs::RevokeAndACK {
1466                 channel_id: chan.2,
1467                 per_commitment_secret: local_secret,
1468                 next_per_commitment_point: next_local_point
1469         };
1470         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1471
1472         let events = nodes[1].node.get_and_clear_pending_msg_events();
1473         assert_eq!(events.len(), 1);
1474         // Make sure the HTLC failed in the way we expect.
1475         match events[0] {
1476                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1477                         assert_eq!(update_fail_htlcs.len(), 1);
1478                         update_fail_htlcs[0].clone()
1479                 },
1480                 _ => panic!("Unexpected event"),
1481         };
1482         nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1483                 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", ::hex::encode(raa_msg.channel_id)), 1);
1484
1485         check_added_monitors!(nodes[1], 2);
1486 }
1487
1488 #[test]
1489 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1490         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1491         // Set the fee rate for the channel very high, to the point where the fundee
1492         // sending any above-dust amount would result in a channel reserve violation.
1493         // In this test we check that we would be prevented from sending an HTLC in
1494         // this situation.
1495         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1496         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1497         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1498         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1499         let default_config = UserConfig::default();
1500         let opt_anchors = false;
1501
1502         let mut push_amt = 100_000_000;
1503         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1504
1505         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1506
1507         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1508
1509         // Sending exactly enough to hit the reserve amount should be accepted
1510         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1511                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1512         }
1513
1514         // However one more HTLC should be significantly over the reserve amount and fail.
1515         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1516         unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)), true, APIError::ChannelUnavailable { ref err },
1517                 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1518         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1519         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send value that would put counterparty balance under holder-announced channel reserve value".to_string(), 1);
1520 }
1521
1522 #[test]
1523 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1524         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1525         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1526         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1527         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1528         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1529         let default_config = UserConfig::default();
1530         let opt_anchors = false;
1531
1532         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1533         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1534         // transaction fee with 0 HTLCs (183 sats)).
1535         let mut push_amt = 100_000_000;
1536         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1537         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1538         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1539
1540         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1541         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1542                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1543         }
1544
1545         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 700_000);
1546         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1547         let secp_ctx = Secp256k1::new();
1548         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1549         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1550         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1551         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 700_000, &Some(payment_secret), cur_height, &None).unwrap();
1552         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1553         let msg = msgs::UpdateAddHTLC {
1554                 channel_id: chan.2,
1555                 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1556                 amount_msat: htlc_msat,
1557                 payment_hash: payment_hash,
1558                 cltv_expiry: htlc_cltv,
1559                 onion_routing_packet: onion_packet,
1560         };
1561
1562         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1563         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1564         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);
1565         assert_eq!(nodes[0].node.list_channels().len(), 0);
1566         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1567         assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1568         check_added_monitors!(nodes[0], 1);
1569         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() });
1570 }
1571
1572 #[test]
1573 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1574         // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1575         // calculating our commitment transaction fee (this was previously broken).
1576         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1577         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1578
1579         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1580         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1581         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1582         let default_config = UserConfig::default();
1583         let opt_anchors = false;
1584
1585         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1586         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1587         // transaction fee with 0 HTLCs (183 sats)).
1588         let mut push_amt = 100_000_000;
1589         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1590         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1591         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1592
1593         let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1594                 + feerate_per_kw as u64 * htlc_success_tx_weight(opt_anchors) / 1000 * 1000 - 1;
1595         // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1596         // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1597         // commitment transaction fee.
1598         let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1599
1600         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1601         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1602                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1603         }
1604
1605         // One more than the dust amt should fail, however.
1606         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt + 1);
1607         unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)), true, APIError::ChannelUnavailable { ref err },
1608                 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1609 }
1610
1611 #[test]
1612 fn test_chan_init_feerate_unaffordability() {
1613         // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to
1614         // channel reserve and feerate requirements.
1615         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1616         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1617         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1618         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1619         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1620         let default_config = UserConfig::default();
1621         let opt_anchors = false;
1622
1623         // Set the push_msat amount such that nodes[0] will not be able to afford to add even a single
1624         // HTLC.
1625         let mut push_amt = 100_000_000;
1626         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1627         assert_eq!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt + 1, 42, None).unwrap_err(),
1628                 APIError::APIMisuseError { err: "Funding amount (356) can't even pay fee for initial commitment transaction fee of 357.".to_string() });
1629
1630         // During open, we don't have a "counterparty channel reserve" to check against, so that
1631         // requirement only comes into play on the open_channel handling side.
1632         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1633         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt, 42, None).unwrap();
1634         let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
1635         open_channel_msg.push_msat += 1;
1636         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_channel_msg);
1637
1638         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1639         assert_eq!(msg_events.len(), 1);
1640         match msg_events[0] {
1641                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1642                         assert_eq!(msg.data, "Insufficient funding amount for initial reserve");
1643                 },
1644                 _ => panic!("Unexpected event"),
1645         }
1646 }
1647
1648 #[test]
1649 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1650         // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1651         // calculating our counterparty's commitment transaction fee (this was previously broken).
1652         let chanmon_cfgs = create_chanmon_cfgs(2);
1653         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1654         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1655         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1656         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1657
1658         let payment_amt = 46000; // Dust amount
1659         // In the previous code, these first four payments would succeed.
1660         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1661         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1662         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1663         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1664
1665         // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1666         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1667         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1668         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1669         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1670         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1671
1672         // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1673         // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1674         // transaction fee and therefore perceived this next payment as a channel reserve violation.
1675         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1676 }
1677
1678 #[test]
1679 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1680         let chanmon_cfgs = create_chanmon_cfgs(3);
1681         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1682         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1683         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1684         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1685         let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1686
1687         let feemsat = 239;
1688         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1689         let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1690         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
1691         let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
1692
1693         // Add a 2* and +1 for the fee spike reserve.
1694         let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1695         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;
1696         let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1697
1698         // Add a pending HTLC.
1699         let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1700         let payment_event_1 = {
1701                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1702                 check_added_monitors!(nodes[0], 1);
1703
1704                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1705                 assert_eq!(events.len(), 1);
1706                 SendEvent::from_event(events.remove(0))
1707         };
1708         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1709
1710         // Attempt to trigger a channel reserve violation --> payment failure.
1711         let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2, opt_anchors);
1712         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;
1713         let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1714         let (route_2, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_2);
1715
1716         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1717         let secp_ctx = Secp256k1::new();
1718         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1719         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1720         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1721         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height, &None).unwrap();
1722         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1723         let msg = msgs::UpdateAddHTLC {
1724                 channel_id: chan.2,
1725                 htlc_id: 1,
1726                 amount_msat: htlc_msat + 1,
1727                 payment_hash: our_payment_hash_1,
1728                 cltv_expiry: htlc_cltv,
1729                 onion_routing_packet: onion_packet,
1730         };
1731
1732         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1733         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1734         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1735         assert_eq!(nodes[1].node.list_channels().len(), 1);
1736         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1737         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1738         check_added_monitors!(nodes[1], 1);
1739         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() });
1740 }
1741
1742 #[test]
1743 fn test_inbound_outbound_capacity_is_not_zero() {
1744         let chanmon_cfgs = create_chanmon_cfgs(2);
1745         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1746         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1747         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1748         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1749         let channels0 = node_chanmgrs[0].list_channels();
1750         let channels1 = node_chanmgrs[1].list_channels();
1751         let default_config = UserConfig::default();
1752         assert_eq!(channels0.len(), 1);
1753         assert_eq!(channels1.len(), 1);
1754
1755         let reserve = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config);
1756         assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1757         assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1758
1759         assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1760         assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1761 }
1762
1763 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64, opt_anchors: bool) -> u64 {
1764         (commitment_tx_base_weight(opt_anchors) + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1765 }
1766
1767 #[test]
1768 fn test_channel_reserve_holding_cell_htlcs() {
1769         let chanmon_cfgs = create_chanmon_cfgs(3);
1770         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1771         // When this test was written, the default base fee floated based on the HTLC count.
1772         // It is now fixed, so we simply set the fee to the expected value here.
1773         let mut config = test_default_channel_config();
1774         config.channel_config.forwarding_fee_base_msat = 239;
1775         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1776         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1777         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1778         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1779
1780         let mut stat01 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1781         let mut stat11 = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
1782
1783         let mut stat12 = get_channel_value_stat!(nodes[1], nodes[2], chan_2.2);
1784         let mut stat22 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
1785
1786         macro_rules! expect_forward {
1787                 ($node: expr) => {{
1788                         let mut events = $node.node.get_and_clear_pending_msg_events();
1789                         assert_eq!(events.len(), 1);
1790                         check_added_monitors!($node, 1);
1791                         let payment_event = SendEvent::from_event(events.remove(0));
1792                         payment_event
1793                 }}
1794         }
1795
1796         let feemsat = 239; // set above
1797         let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1798         let feerate = get_feerate!(nodes[0], nodes[1], chan_1.2);
1799         let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan_1.2);
1800
1801         let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1802
1803         // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1804         {
1805                 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id())
1806                         .with_features(channelmanager::provided_invoice_features()).with_max_channel_saturation_power_of_half(0);
1807                 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], payment_params, recv_value_0, TEST_FINAL_CLTV);
1808                 route.paths[0].last_mut().unwrap().fee_msat += 1;
1809                 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1810
1811                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)), true, APIError::ChannelUnavailable { ref err },
1812                         assert!(regex::Regex::new(r"Cannot send value that would put us over the max HTLC value in flight our peer will accept \(\d+\)").unwrap().is_match(err)));
1813                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1814                 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send value that would put us over the max HTLC value in flight our peer will accept".to_string(), 1);
1815         }
1816
1817         // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1818         // nodes[0]'s wealth
1819         loop {
1820                 let amt_msat = recv_value_0 + total_fee_msat;
1821                 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1822                 // Also, ensure that each payment has enough to be over the dust limit to
1823                 // ensure it'll be included in each commit tx fee calculation.
1824                 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1825                 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1826                 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1827                         break;
1828                 }
1829
1830                 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id())
1831                         .with_features(channelmanager::provided_invoice_features()).with_max_channel_saturation_power_of_half(0);
1832                 let route = get_route!(nodes[0], payment_params, recv_value_0, TEST_FINAL_CLTV).unwrap();
1833                 let (payment_preimage, ..) = send_along_route(&nodes[0], route, &[&nodes[1], &nodes[2]], recv_value_0);
1834                 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1835
1836                 let (stat01_, stat11_, stat12_, stat22_) = (
1837                         get_channel_value_stat!(nodes[0], nodes[1], chan_1.2),
1838                         get_channel_value_stat!(nodes[1], nodes[0], chan_1.2),
1839                         get_channel_value_stat!(nodes[1], nodes[2], chan_2.2),
1840                         get_channel_value_stat!(nodes[2], nodes[1], chan_2.2),
1841                 );
1842
1843                 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1844                 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1845                 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1846                 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1847                 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1848         }
1849
1850         // adding pending output.
1851         // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1852         // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1853         // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1854         // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1855         // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1856         // cases where 1 msat over X amount will cause a payment failure, but anything less than
1857         // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1858         // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1859         // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1860         // policy.
1861         let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1862         let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1863         let amt_msat_1 = recv_value_1 + total_fee_msat;
1864
1865         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);
1866         let payment_event_1 = {
1867                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1868                 check_added_monitors!(nodes[0], 1);
1869
1870                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1871                 assert_eq!(events.len(), 1);
1872                 SendEvent::from_event(events.remove(0))
1873         };
1874         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1875
1876         // channel reserve test with htlc pending output > 0
1877         let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1878         {
1879                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_2 + 1);
1880                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)), true, APIError::ChannelUnavailable { ref err },
1881                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1882                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1883         }
1884
1885         // split the rest to test holding cell
1886         let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1887         let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1888         let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1889         let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1890         {
1891                 let stat = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1892                 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);
1893         }
1894
1895         // now see if they go through on both sides
1896         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);
1897         // but this will stuck in the holding cell
1898         nodes[0].node.send_payment(&route_21, our_payment_hash_21, &Some(our_payment_secret_21), PaymentId(our_payment_hash_21.0)).unwrap();
1899         check_added_monitors!(nodes[0], 0);
1900         let events = nodes[0].node.get_and_clear_pending_events();
1901         assert_eq!(events.len(), 0);
1902
1903         // test with outbound holding cell amount > 0
1904         {
1905                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22+1);
1906                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)), true, APIError::ChannelUnavailable { ref err },
1907                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1908                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1909                 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send value that would put our balance under counterparty-announced channel reserve value".to_string(), 2);
1910         }
1911
1912         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);
1913         // this will also stuck in the holding cell
1914         nodes[0].node.send_payment(&route_22, our_payment_hash_22, &Some(our_payment_secret_22), PaymentId(our_payment_hash_22.0)).unwrap();
1915         check_added_monitors!(nodes[0], 0);
1916         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1917         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1918
1919         // flush the pending htlc
1920         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1921         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1922         check_added_monitors!(nodes[1], 1);
1923
1924         // the pending htlc should be promoted to committed
1925         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1926         check_added_monitors!(nodes[0], 1);
1927         let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1928
1929         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1930         let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1931         // No commitment_signed so get_event_msg's assert(len == 1) passes
1932         check_added_monitors!(nodes[0], 1);
1933
1934         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1935         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1936         check_added_monitors!(nodes[1], 1);
1937
1938         expect_pending_htlcs_forwardable!(nodes[1]);
1939
1940         let ref payment_event_11 = expect_forward!(nodes[1]);
1941         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1942         commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1943
1944         expect_pending_htlcs_forwardable!(nodes[2]);
1945         expect_payment_claimable!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
1946
1947         // flush the htlcs in the holding cell
1948         assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1949         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1950         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1951         commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1952         expect_pending_htlcs_forwardable!(nodes[1]);
1953
1954         let ref payment_event_3 = expect_forward!(nodes[1]);
1955         assert_eq!(payment_event_3.msgs.len(), 2);
1956         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1957         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1958
1959         commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1960         expect_pending_htlcs_forwardable!(nodes[2]);
1961
1962         let events = nodes[2].node.get_and_clear_pending_events();
1963         assert_eq!(events.len(), 2);
1964         match events[0] {
1965                 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, via_user_channel_id: _ } => {
1966                         assert_eq!(our_payment_hash_21, *payment_hash);
1967                         assert_eq!(recv_value_21, amount_msat);
1968                         assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
1969                         assert_eq!(via_channel_id, Some(chan_2.2));
1970                         match &purpose {
1971                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1972                                         assert!(payment_preimage.is_none());
1973                                         assert_eq!(our_payment_secret_21, *payment_secret);
1974                                 },
1975                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
1976                         }
1977                 },
1978                 _ => panic!("Unexpected event"),
1979         }
1980         match events[1] {
1981                 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, via_user_channel_id: _ } => {
1982                         assert_eq!(our_payment_hash_22, *payment_hash);
1983                         assert_eq!(recv_value_22, amount_msat);
1984                         assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
1985                         assert_eq!(via_channel_id, Some(chan_2.2));
1986                         match &purpose {
1987                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1988                                         assert!(payment_preimage.is_none());
1989                                         assert_eq!(our_payment_secret_22, *payment_secret);
1990                                 },
1991                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
1992                         }
1993                 },
1994                 _ => panic!("Unexpected event"),
1995         }
1996
1997         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
1998         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
1999         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
2000
2001         let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1, opt_anchors);
2002         let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2003         send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
2004
2005         let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
2006         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);
2007         let stat0 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
2008         assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2009         assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2010
2011         let stat2 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
2012         assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2013 }
2014
2015 #[test]
2016 fn channel_reserve_in_flight_removes() {
2017         // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2018         // can send to its counterparty, but due to update ordering, the other side may not yet have
2019         // considered those HTLCs fully removed.
2020         // This tests that we don't count HTLCs which will not be included in the next remote
2021         // commitment transaction towards the reserve value (as it implies no commitment transaction
2022         // will be generated which violates the remote reserve value).
2023         // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2024         // To test this we:
2025         //  * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2026         //    you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2027         //    you only consider the value of the first HTLC, it may not),
2028         //  * start routing a third HTLC from A to B,
2029         //  * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2030         //    the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2031         //  * deliver the first fulfill from B
2032         //  * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2033         //    claim,
2034         //  * deliver A's response CS and RAA.
2035         //    This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2036         //    removed it fully. B now has the push_msat plus the first two HTLCs in value.
2037         //  * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2038         //    of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2039         let chanmon_cfgs = create_chanmon_cfgs(2);
2040         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2041         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2042         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2043         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2044
2045         let b_chan_values = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
2046         // Route the first two HTLCs.
2047         let payment_value_1 = b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000;
2048         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], payment_value_1);
2049         let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20_000);
2050
2051         // Start routing the third HTLC (this is just used to get everyone in the right state).
2052         let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
2053         let send_1 = {
2054                 nodes[0].node.send_payment(&route, payment_hash_3, &Some(payment_secret_3), PaymentId(payment_hash_3.0)).unwrap();
2055                 check_added_monitors!(nodes[0], 1);
2056                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2057                 assert_eq!(events.len(), 1);
2058                 SendEvent::from_event(events.remove(0))
2059         };
2060
2061         // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2062         // initial fulfill/CS.
2063         nodes[1].node.claim_funds(payment_preimage_1);
2064         expect_payment_claimed!(nodes[1], payment_hash_1, payment_value_1);
2065         check_added_monitors!(nodes[1], 1);
2066         let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2067
2068         // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2069         // remove the second HTLC when we send the HTLC back from B to A.
2070         nodes[1].node.claim_funds(payment_preimage_2);
2071         expect_payment_claimed!(nodes[1], payment_hash_2, 20_000);
2072         check_added_monitors!(nodes[1], 1);
2073         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2074
2075         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2076         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2077         check_added_monitors!(nodes[0], 1);
2078         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2079         expect_payment_sent_without_paths!(nodes[0], payment_preimage_1);
2080
2081         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2082         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2083         check_added_monitors!(nodes[1], 1);
2084         // B is already AwaitingRAA, so cant generate a CS here
2085         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2086
2087         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2088         check_added_monitors!(nodes[1], 1);
2089         let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2090
2091         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2092         check_added_monitors!(nodes[0], 1);
2093         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2094
2095         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2096         check_added_monitors!(nodes[1], 1);
2097         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2098
2099         // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2100         // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2101         // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2102         // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2103         // on-chain as necessary).
2104         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2105         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2106         check_added_monitors!(nodes[0], 1);
2107         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2108         expect_payment_sent_without_paths!(nodes[0], payment_preimage_2);
2109
2110         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2111         check_added_monitors!(nodes[1], 1);
2112         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2113
2114         expect_pending_htlcs_forwardable!(nodes[1]);
2115         expect_payment_claimable!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2116
2117         // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2118         // resolve the second HTLC from A's point of view.
2119         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2120         check_added_monitors!(nodes[0], 1);
2121         expect_payment_path_successful!(nodes[0]);
2122         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2123
2124         // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2125         // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2126         let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2127         let send_2 = {
2128                 nodes[1].node.send_payment(&route, payment_hash_4, &Some(payment_secret_4), PaymentId(payment_hash_4.0)).unwrap();
2129                 check_added_monitors!(nodes[1], 1);
2130                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2131                 assert_eq!(events.len(), 1);
2132                 SendEvent::from_event(events.remove(0))
2133         };
2134
2135         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2136         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2137         check_added_monitors!(nodes[0], 1);
2138         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2139
2140         // Now just resolve all the outstanding messages/HTLCs for completeness...
2141
2142         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2143         check_added_monitors!(nodes[1], 1);
2144         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2145
2146         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2147         check_added_monitors!(nodes[1], 1);
2148
2149         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2150         check_added_monitors!(nodes[0], 1);
2151         expect_payment_path_successful!(nodes[0]);
2152         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2153
2154         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2155         check_added_monitors!(nodes[1], 1);
2156         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2157
2158         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2159         check_added_monitors!(nodes[0], 1);
2160
2161         expect_pending_htlcs_forwardable!(nodes[0]);
2162         expect_payment_claimable!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2163
2164         claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2165         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2166 }
2167
2168 #[test]
2169 fn channel_monitor_network_test() {
2170         // Simple test which builds a network of ChannelManagers, connects them to each other, and
2171         // tests that ChannelMonitor is able to recover from various states.
2172         let chanmon_cfgs = create_chanmon_cfgs(5);
2173         let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2174         let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2175         let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2176
2177         // Create some initial channels
2178         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2179         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2180         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2181         let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2182
2183         // Make sure all nodes are at the same starting height
2184         connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2185         connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2186         connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2187         connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2188         connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2189
2190         // Rebalance the network a bit by relaying one payment through all the channels...
2191         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2192         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2193         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2194         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2195
2196         // Simple case with no pending HTLCs:
2197         nodes[1].node.force_close_broadcasting_latest_txn(&chan_1.2, &nodes[0].node.get_our_node_id()).unwrap();
2198         check_added_monitors!(nodes[1], 1);
2199         check_closed_broadcast!(nodes[1], true);
2200         {
2201                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2202                 assert_eq!(node_txn.len(), 1);
2203                 mine_transaction(&nodes[0], &node_txn[0]);
2204                 check_added_monitors!(nodes[0], 1);
2205                 test_txn_broadcast(&nodes[0], &chan_1, Some(node_txn[0].clone()), HTLCType::NONE);
2206         }
2207         check_closed_broadcast!(nodes[0], true);
2208         assert_eq!(nodes[0].node.list_channels().len(), 0);
2209         assert_eq!(nodes[1].node.list_channels().len(), 1);
2210         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2211         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2212
2213         // One pending HTLC is discarded by the force-close:
2214         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[1], &[&nodes[2], &nodes[3]], 3_000_000);
2215
2216         // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2217         // broadcasted until we reach the timelock time).
2218         nodes[1].node.force_close_broadcasting_latest_txn(&chan_2.2, &nodes[2].node.get_our_node_id()).unwrap();
2219         check_closed_broadcast!(nodes[1], true);
2220         check_added_monitors!(nodes[1], 1);
2221         {
2222                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2223                 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2224                 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2225                 mine_transaction(&nodes[2], &node_txn[0]);
2226                 check_added_monitors!(nodes[2], 1);
2227                 test_txn_broadcast(&nodes[2], &chan_2, Some(node_txn[0].clone()), HTLCType::NONE);
2228         }
2229         check_closed_broadcast!(nodes[2], true);
2230         assert_eq!(nodes[1].node.list_channels().len(), 0);
2231         assert_eq!(nodes[2].node.list_channels().len(), 1);
2232         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2233         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2234
2235         macro_rules! claim_funds {
2236                 ($node: expr, $prev_node: expr, $preimage: expr, $payment_hash: expr) => {
2237                         {
2238                                 $node.node.claim_funds($preimage);
2239                                 expect_payment_claimed!($node, $payment_hash, 3_000_000);
2240                                 check_added_monitors!($node, 1);
2241
2242                                 let events = $node.node.get_and_clear_pending_msg_events();
2243                                 assert_eq!(events.len(), 1);
2244                                 match events[0] {
2245                                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2246                                                 assert!(update_add_htlcs.is_empty());
2247                                                 assert!(update_fail_htlcs.is_empty());
2248                                                 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2249                                         },
2250                                         _ => panic!("Unexpected event"),
2251                                 };
2252                         }
2253                 }
2254         }
2255
2256         // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2257         // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2258         nodes[2].node.force_close_broadcasting_latest_txn(&chan_3.2, &nodes[3].node.get_our_node_id()).unwrap();
2259         check_added_monitors!(nodes[2], 1);
2260         check_closed_broadcast!(nodes[2], true);
2261         let node2_commitment_txid;
2262         {
2263                 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2264                 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2265                 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2266                 node2_commitment_txid = node_txn[0].txid();
2267
2268                 // Claim the payment on nodes[3], giving it knowledge of the preimage
2269                 claim_funds!(nodes[3], nodes[2], payment_preimage_1, payment_hash_1);
2270                 mine_transaction(&nodes[3], &node_txn[0]);
2271                 check_added_monitors!(nodes[3], 1);
2272                 check_preimage_claim(&nodes[3], &node_txn);
2273         }
2274         check_closed_broadcast!(nodes[3], true);
2275         assert_eq!(nodes[2].node.list_channels().len(), 0);
2276         assert_eq!(nodes[3].node.list_channels().len(), 1);
2277         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
2278         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2279
2280         // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2281         // confusing us in the following tests.
2282         let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2283
2284         // One pending HTLC to time out:
2285         let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[3], &[&nodes[4]], 3_000_000);
2286         // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2287         // buffer space).
2288
2289         let (close_chan_update_1, close_chan_update_2) = {
2290                 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2291                 let events = nodes[3].node.get_and_clear_pending_msg_events();
2292                 assert_eq!(events.len(), 2);
2293                 let close_chan_update_1 = match events[0] {
2294                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2295                                 msg.clone()
2296                         },
2297                         _ => panic!("Unexpected event"),
2298                 };
2299                 match events[1] {
2300                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2301                                 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2302                         },
2303                         _ => panic!("Unexpected event"),
2304                 }
2305                 check_added_monitors!(nodes[3], 1);
2306
2307                 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2308                 {
2309                         let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2310                         node_txn.retain(|tx| {
2311                                 if tx.input[0].previous_output.txid == node2_commitment_txid {
2312                                         false
2313                                 } else { true }
2314                         });
2315                 }
2316
2317                 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2318
2319                 // Claim the payment on nodes[4], giving it knowledge of the preimage
2320                 claim_funds!(nodes[4], nodes[3], payment_preimage_2, payment_hash_2);
2321
2322                 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2323                 let events = nodes[4].node.get_and_clear_pending_msg_events();
2324                 assert_eq!(events.len(), 2);
2325                 let close_chan_update_2 = match events[0] {
2326                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2327                                 msg.clone()
2328                         },
2329                         _ => panic!("Unexpected event"),
2330                 };
2331                 match events[1] {
2332                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2333                                 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2334                         },
2335                         _ => panic!("Unexpected event"),
2336                 }
2337                 check_added_monitors!(nodes[4], 1);
2338                 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2339
2340                 mine_transaction(&nodes[4], &node_txn[0]);
2341                 check_preimage_claim(&nodes[4], &node_txn);
2342                 (close_chan_update_1, close_chan_update_2)
2343         };
2344         nodes[3].gossip_sync.handle_channel_update(&close_chan_update_2).unwrap();
2345         nodes[4].gossip_sync.handle_channel_update(&close_chan_update_1).unwrap();
2346         assert_eq!(nodes[3].node.list_channels().len(), 0);
2347         assert_eq!(nodes[4].node.list_channels().len(), 0);
2348
2349         assert_eq!(nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon),
2350                 ChannelMonitorUpdateStatus::Completed);
2351         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2352         check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed);
2353 }
2354
2355 #[test]
2356 fn test_justice_tx() {
2357         // Test justice txn built on revoked HTLC-Success tx, against both sides
2358         let mut alice_config = UserConfig::default();
2359         alice_config.channel_handshake_config.announced_channel = true;
2360         alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2361         alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2362         let mut bob_config = UserConfig::default();
2363         bob_config.channel_handshake_config.announced_channel = true;
2364         bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2365         bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2366         let user_cfgs = [Some(alice_config), Some(bob_config)];
2367         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2368         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2369         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2370         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2371         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2372         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2373         *nodes[0].connect_style.borrow_mut() = ConnectStyle::FullBlockViaListen;
2374         // Create some new channels:
2375         let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2376
2377         // A pending HTLC which will be revoked:
2378         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2379         // Get the will-be-revoked local txn from nodes[0]
2380         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2381         assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2382         assert_eq!(revoked_local_txn[0].input.len(), 1);
2383         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2384         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2385         assert_eq!(revoked_local_txn[1].input.len(), 1);
2386         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2387         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2388         // Revoke the old state
2389         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2390
2391         {
2392                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2393                 {
2394                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2395                         assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2396                         assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2397
2398                         check_spends!(node_txn[0], revoked_local_txn[0]);
2399                         node_txn.swap_remove(0);
2400                 }
2401                 check_added_monitors!(nodes[1], 1);
2402                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2403                 test_txn_broadcast(&nodes[1], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2404
2405                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2406                 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2407                 // Verify broadcast of revoked HTLC-timeout
2408                 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2409                 check_added_monitors!(nodes[0], 1);
2410                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2411                 // Broadcast revoked HTLC-timeout on node 1
2412                 mine_transaction(&nodes[1], &node_txn[1]);
2413                 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2414         }
2415         get_announce_close_broadcast_events(&nodes, 0, 1);
2416
2417         assert_eq!(nodes[0].node.list_channels().len(), 0);
2418         assert_eq!(nodes[1].node.list_channels().len(), 0);
2419
2420         // We test justice_tx build by A on B's revoked HTLC-Success tx
2421         // Create some new channels:
2422         let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2423         {
2424                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2425                 node_txn.clear();
2426         }
2427
2428         // A pending HTLC which will be revoked:
2429         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2430         // Get the will-be-revoked local txn from B
2431         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2432         assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2433         assert_eq!(revoked_local_txn[0].input.len(), 1);
2434         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2435         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2436         // Revoke the old state
2437         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2438         {
2439                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2440                 {
2441                         let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2442                         assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2443                         assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2444
2445                         check_spends!(node_txn[0], revoked_local_txn[0]);
2446                         node_txn.swap_remove(0);
2447                 }
2448                 check_added_monitors!(nodes[0], 1);
2449                 test_txn_broadcast(&nodes[0], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2450
2451                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2452                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2453                 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2454                 check_added_monitors!(nodes[1], 1);
2455                 mine_transaction(&nodes[0], &node_txn[1]);
2456                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2457                 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2458         }
2459         get_announce_close_broadcast_events(&nodes, 0, 1);
2460         assert_eq!(nodes[0].node.list_channels().len(), 0);
2461         assert_eq!(nodes[1].node.list_channels().len(), 0);
2462 }
2463
2464 #[test]
2465 fn revoked_output_claim() {
2466         // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2467         // transaction is broadcast by its counterparty
2468         let chanmon_cfgs = create_chanmon_cfgs(2);
2469         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2470         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2471         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2472         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2473         // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2474         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2475         assert_eq!(revoked_local_txn.len(), 1);
2476         // Only output is the full channel value back to nodes[0]:
2477         assert_eq!(revoked_local_txn[0].output.len(), 1);
2478         // Send a payment through, updating everyone's latest commitment txn
2479         send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2480
2481         // Inform nodes[1] that nodes[0] broadcast a stale tx
2482         mine_transaction(&nodes[1], &revoked_local_txn[0]);
2483         check_added_monitors!(nodes[1], 1);
2484         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2485         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2486         assert_eq!(node_txn.len(), 1); // ChannelMonitor: justice tx against revoked to_local output
2487
2488         check_spends!(node_txn[0], revoked_local_txn[0]);
2489
2490         // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2491         mine_transaction(&nodes[0], &revoked_local_txn[0]);
2492         get_announce_close_broadcast_events(&nodes, 0, 1);
2493         check_added_monitors!(nodes[0], 1);
2494         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2495 }
2496
2497 #[test]
2498 fn claim_htlc_outputs_shared_tx() {
2499         // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2500         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2501         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2502         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2503         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2504         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2505
2506         // Create some new channel:
2507         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2508
2509         // Rebalance the network to generate htlc in the two directions
2510         send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2511         // 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
2512         let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2513         let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2514
2515         // Get the will-be-revoked local txn from node[0]
2516         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2517         assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2518         assert_eq!(revoked_local_txn[0].input.len(), 1);
2519         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2520         assert_eq!(revoked_local_txn[1].input.len(), 1);
2521         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2522         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2523         check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2524
2525         //Revoke the old state
2526         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2527
2528         {
2529                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2530                 check_added_monitors!(nodes[0], 1);
2531                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2532                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2533                 check_added_monitors!(nodes[1], 1);
2534                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2535                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2536                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2537
2538                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2539                 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2540
2541                 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2542                 check_spends!(node_txn[0], revoked_local_txn[0]);
2543
2544                 let mut witness_lens = BTreeSet::new();
2545                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2546                 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2547                 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2548                 assert_eq!(witness_lens.len(), 3);
2549                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2550                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2551                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2552
2553                 // Finally, mine the penalty transaction and check that we get an HTLC failure after
2554                 // ANTI_REORG_DELAY confirmations.
2555                 mine_transaction(&nodes[1], &node_txn[0]);
2556                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2557                 expect_payment_failed!(nodes[1], payment_hash_2, false);
2558         }
2559         get_announce_close_broadcast_events(&nodes, 0, 1);
2560         assert_eq!(nodes[0].node.list_channels().len(), 0);
2561         assert_eq!(nodes[1].node.list_channels().len(), 0);
2562 }
2563
2564 #[test]
2565 fn claim_htlc_outputs_single_tx() {
2566         // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2567         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2568         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2569         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2570         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2571         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2572
2573         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2574
2575         // Rebalance the network to generate htlc in the two directions
2576         send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2577         // 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
2578         // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2579         let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2580         let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2581
2582         // Get the will-be-revoked local txn from node[0]
2583         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2584
2585         //Revoke the old state
2586         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2587
2588         {
2589                 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2590                 check_added_monitors!(nodes[0], 1);
2591                 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2592                 check_added_monitors!(nodes[1], 1);
2593                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2594                 let mut events = nodes[0].node.get_and_clear_pending_events();
2595                 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2596                 match events.last().unwrap() {
2597                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2598                         _ => panic!("Unexpected event"),
2599                 }
2600
2601                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2602                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2603
2604                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2605                 assert_eq!(node_txn.len(), 7);
2606
2607                 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2608                 assert_eq!(node_txn[0].input.len(), 1);
2609                 check_spends!(node_txn[0], chan_1.3);
2610                 assert_eq!(node_txn[1].input.len(), 1);
2611                 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2612                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2613                 check_spends!(node_txn[1], node_txn[0]);
2614
2615                 // Justice transactions are indices 2-3-4
2616                 assert_eq!(node_txn[2].input.len(), 1);
2617                 assert_eq!(node_txn[3].input.len(), 1);
2618                 assert_eq!(node_txn[4].input.len(), 1);
2619
2620                 check_spends!(node_txn[2], revoked_local_txn[0]);
2621                 check_spends!(node_txn[3], revoked_local_txn[0]);
2622                 check_spends!(node_txn[4], revoked_local_txn[0]);
2623
2624                 let mut witness_lens = BTreeSet::new();
2625                 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2626                 witness_lens.insert(node_txn[3].input[0].witness.last().unwrap().len());
2627                 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2628                 assert_eq!(witness_lens.len(), 3);
2629                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2630                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2631                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2632
2633                 // Finally, mine the penalty transactions and check that we get an HTLC failure after
2634                 // ANTI_REORG_DELAY confirmations.
2635                 mine_transaction(&nodes[1], &node_txn[2]);
2636                 mine_transaction(&nodes[1], &node_txn[3]);
2637                 mine_transaction(&nodes[1], &node_txn[4]);
2638                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2639                 expect_payment_failed!(nodes[1], payment_hash_2, false);
2640         }
2641         get_announce_close_broadcast_events(&nodes, 0, 1);
2642         assert_eq!(nodes[0].node.list_channels().len(), 0);
2643         assert_eq!(nodes[1].node.list_channels().len(), 0);
2644 }
2645
2646 #[test]
2647 fn test_htlc_on_chain_success() {
2648         // Test that in case of a unilateral close onchain, we detect the state of output and pass
2649         // the preimage backward accordingly. So here we test that ChannelManager is
2650         // broadcasting the right event to other nodes in payment path.
2651         // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2652         // A --------------------> B ----------------------> C (preimage)
2653         // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2654         // commitment transaction was broadcast.
2655         // Then, B should learn the preimage from said transactions, attempting to claim backwards
2656         // towards B.
2657         // B should be able to claim via preimage if A then broadcasts its local tx.
2658         // Finally, when A sees B's latest local commitment transaction it should be able to claim
2659         // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2660         // PaymentSent event).
2661
2662         let chanmon_cfgs = create_chanmon_cfgs(3);
2663         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2664         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2665         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2666
2667         // Create some initial channels
2668         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2669         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2670
2671         // Ensure all nodes are at the same height
2672         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2673         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2674         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2675         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2676
2677         // Rebalance the network a bit by relaying one payment through all the channels...
2678         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2679         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2680
2681         let (our_payment_preimage, payment_hash_1, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2682         let (our_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2683
2684         // Broadcast legit commitment tx from C on B's chain
2685         // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2686         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2687         assert_eq!(commitment_tx.len(), 1);
2688         check_spends!(commitment_tx[0], chan_2.3);
2689         nodes[2].node.claim_funds(our_payment_preimage);
2690         expect_payment_claimed!(nodes[2], payment_hash_1, 3_000_000);
2691         nodes[2].node.claim_funds(our_payment_preimage_2);
2692         expect_payment_claimed!(nodes[2], payment_hash_2, 3_000_000);
2693         check_added_monitors!(nodes[2], 2);
2694         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2695         assert!(updates.update_add_htlcs.is_empty());
2696         assert!(updates.update_fail_htlcs.is_empty());
2697         assert!(updates.update_fail_malformed_htlcs.is_empty());
2698         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2699
2700         mine_transaction(&nodes[2], &commitment_tx[0]);
2701         check_closed_broadcast!(nodes[2], true);
2702         check_added_monitors!(nodes[2], 1);
2703         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2704         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 2 (2 * HTLC-Success tx)
2705         assert_eq!(node_txn.len(), 2);
2706         check_spends!(node_txn[0], commitment_tx[0]);
2707         check_spends!(node_txn[1], commitment_tx[0]);
2708         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2709         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2710         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2711         assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2712         assert_eq!(node_txn[0].lock_time.0, 0);
2713         assert_eq!(node_txn[1].lock_time.0, 0);
2714
2715         // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2716         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
2717         connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone(), node_txn[0].clone(), node_txn[1].clone()]});
2718         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2719         {
2720                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2721                 assert_eq!(added_monitors.len(), 1);
2722                 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2723                 added_monitors.clear();
2724         }
2725         let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2726         assert_eq!(forwarded_events.len(), 3);
2727         match forwarded_events[0] {
2728                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2729                 _ => panic!("Unexpected event"),
2730         }
2731         let chan_id = Some(chan_1.2);
2732         match forwarded_events[1] {
2733                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
2734                         assert_eq!(fee_earned_msat, Some(1000));
2735                         assert_eq!(prev_channel_id, chan_id);
2736                         assert_eq!(claim_from_onchain_tx, true);
2737                         assert_eq!(next_channel_id, Some(chan_2.2));
2738                 },
2739                 _ => panic!()
2740         }
2741         match forwarded_events[2] {
2742                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
2743                         assert_eq!(fee_earned_msat, Some(1000));
2744                         assert_eq!(prev_channel_id, chan_id);
2745                         assert_eq!(claim_from_onchain_tx, true);
2746                         assert_eq!(next_channel_id, Some(chan_2.2));
2747                 },
2748                 _ => panic!()
2749         }
2750         let events = nodes[1].node.get_and_clear_pending_msg_events();
2751         {
2752                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2753                 assert_eq!(added_monitors.len(), 2);
2754                 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2755                 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2756                 added_monitors.clear();
2757         }
2758         assert_eq!(events.len(), 3);
2759         match events[0] {
2760                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2761                 _ => panic!("Unexpected event"),
2762         }
2763         match events[1] {
2764                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2765                 _ => panic!("Unexpected event"),
2766         }
2767
2768         match events[2] {
2769                 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, .. } } => {
2770                         assert!(update_add_htlcs.is_empty());
2771                         assert!(update_fail_htlcs.is_empty());
2772                         assert_eq!(update_fulfill_htlcs.len(), 1);
2773                         assert!(update_fail_malformed_htlcs.is_empty());
2774                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2775                 },
2776                 _ => panic!("Unexpected event"),
2777         };
2778         macro_rules! check_tx_local_broadcast {
2779                 ($node: expr, $htlc_offered: expr, $commitment_tx: expr) => { {
2780                         let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2781                         assert_eq!(node_txn.len(), 2);
2782                         // Node[1]: 2 * HTLC-timeout tx
2783                         // Node[0]: 2 * HTLC-timeout tx
2784                         check_spends!(node_txn[0], $commitment_tx);
2785                         check_spends!(node_txn[1], $commitment_tx);
2786                         assert_ne!(node_txn[0].lock_time.0, 0);
2787                         assert_ne!(node_txn[1].lock_time.0, 0);
2788                         if $htlc_offered {
2789                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2790                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2791                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2792                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2793                         } else {
2794                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2795                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2796                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2797                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2798                         }
2799                         node_txn.clear();
2800                 } }
2801         }
2802         // nodes[1] now broadcasts its own timeout-claim of the output that nodes[2] just claimed via success.
2803         check_tx_local_broadcast!(nodes[1], false, commitment_tx[0]);
2804
2805         // Broadcast legit commitment tx from A on B's chain
2806         // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
2807         let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2808         check_spends!(node_a_commitment_tx[0], chan_1.3);
2809         mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2810         check_closed_broadcast!(nodes[1], true);
2811         check_added_monitors!(nodes[1], 1);
2812         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2813         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2814         assert!(node_txn.len() == 1 || node_txn.len() == 3); // HTLC-Success, 2* RBF bumps of above HTLC txn
2815         let commitment_spend =
2816                 if node_txn.len() == 1 {
2817                         &node_txn[0]
2818                 } else {
2819                         // Certain `ConnectStyle`s will cause RBF bumps of the previous HTLC transaction to be broadcast.
2820                         // FullBlockViaListen
2821                         if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2822                                 check_spends!(node_txn[1], commitment_tx[0]);
2823                                 check_spends!(node_txn[2], commitment_tx[0]);
2824                                 assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2825                                 &node_txn[0]
2826                         } else {
2827                                 check_spends!(node_txn[0], commitment_tx[0]);
2828                                 check_spends!(node_txn[1], commitment_tx[0]);
2829                                 assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2830                                 &node_txn[2]
2831                         }
2832                 };
2833
2834         check_spends!(commitment_spend, node_a_commitment_tx[0]);
2835         assert_eq!(commitment_spend.input.len(), 2);
2836         assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2837         assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2838         assert_eq!(commitment_spend.lock_time.0, 0);
2839         assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2840         // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2841         // we already checked the same situation with A.
2842
2843         // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2844         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
2845         connect_block(&nodes[0], &Block { header, txdata: vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()] });
2846         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2847         check_closed_broadcast!(nodes[0], true);
2848         check_added_monitors!(nodes[0], 1);
2849         let events = nodes[0].node.get_and_clear_pending_events();
2850         assert_eq!(events.len(), 5);
2851         let mut first_claimed = false;
2852         for event in events {
2853                 match event {
2854                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
2855                                 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
2856                                         assert!(!first_claimed);
2857                                         first_claimed = true;
2858                                 } else {
2859                                         assert_eq!(payment_preimage, our_payment_preimage_2);
2860                                         assert_eq!(payment_hash, payment_hash_2);
2861                                 }
2862                         },
2863                         Event::PaymentPathSuccessful { .. } => {},
2864                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
2865                         _ => panic!("Unexpected event"),
2866                 }
2867         }
2868         check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0]);
2869 }
2870
2871 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2872         // Test that in case of a unilateral close onchain, we detect the state of output and
2873         // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2874         // broadcasting the right event to other nodes in payment path.
2875         // A ------------------> B ----------------------> C (timeout)
2876         //    B's commitment tx                 C's commitment tx
2877         //            \                                  \
2878         //         B's HTLC timeout tx               B's timeout tx
2879
2880         let chanmon_cfgs = create_chanmon_cfgs(3);
2881         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2882         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2883         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2884         *nodes[0].connect_style.borrow_mut() = connect_style;
2885         *nodes[1].connect_style.borrow_mut() = connect_style;
2886         *nodes[2].connect_style.borrow_mut() = connect_style;
2887
2888         // Create some intial channels
2889         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2890         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2891
2892         // Rebalance the network a bit by relaying one payment thorugh all the channels...
2893         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2894         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2895
2896         let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2897
2898         // Broadcast legit commitment tx from C on B's chain
2899         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2900         check_spends!(commitment_tx[0], chan_2.3);
2901         nodes[2].node.fail_htlc_backwards(&payment_hash);
2902         check_added_monitors!(nodes[2], 0);
2903         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }]);
2904         check_added_monitors!(nodes[2], 1);
2905
2906         let events = nodes[2].node.get_and_clear_pending_msg_events();
2907         assert_eq!(events.len(), 1);
2908         match events[0] {
2909                 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, .. } } => {
2910                         assert!(update_add_htlcs.is_empty());
2911                         assert!(!update_fail_htlcs.is_empty());
2912                         assert!(update_fulfill_htlcs.is_empty());
2913                         assert!(update_fail_malformed_htlcs.is_empty());
2914                         assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2915                 },
2916                 _ => panic!("Unexpected event"),
2917         };
2918         mine_transaction(&nodes[2], &commitment_tx[0]);
2919         check_closed_broadcast!(nodes[2], true);
2920         check_added_monitors!(nodes[2], 1);
2921         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2922         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2923         assert_eq!(node_txn.len(), 0);
2924
2925         // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2926         // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2927         connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2928         mine_transaction(&nodes[1], &commitment_tx[0]);
2929         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2930         let timeout_tx;
2931         {
2932                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2933                 assert_eq!(node_txn.len(), 3); // 2 (local commitment tx + HTLC-timeout), 1 timeout tx
2934
2935                 check_spends!(node_txn[2], commitment_tx[0]);
2936                 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2937
2938                 check_spends!(node_txn[0], chan_2.3);
2939                 check_spends!(node_txn[1], node_txn[0]);
2940                 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2941                 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2942
2943                 timeout_tx = node_txn[2].clone();
2944                 node_txn.clear();
2945         }
2946
2947         mine_transaction(&nodes[1], &timeout_tx);
2948         check_added_monitors!(nodes[1], 1);
2949         check_closed_broadcast!(nodes[1], true);
2950
2951         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2952
2953         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 }]);
2954         check_added_monitors!(nodes[1], 1);
2955         let events = nodes[1].node.get_and_clear_pending_msg_events();
2956         assert_eq!(events.len(), 1);
2957         match events[0] {
2958                 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, .. } } => {
2959                         assert!(update_add_htlcs.is_empty());
2960                         assert!(!update_fail_htlcs.is_empty());
2961                         assert!(update_fulfill_htlcs.is_empty());
2962                         assert!(update_fail_malformed_htlcs.is_empty());
2963                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2964                 },
2965                 _ => panic!("Unexpected event"),
2966         };
2967
2968         // Broadcast legit commitment tx from B on A's chain
2969         let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
2970         check_spends!(commitment_tx[0], chan_1.3);
2971
2972         mine_transaction(&nodes[0], &commitment_tx[0]);
2973         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2974
2975         check_closed_broadcast!(nodes[0], true);
2976         check_added_monitors!(nodes[0], 1);
2977         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2978         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // 1 timeout tx
2979         assert_eq!(node_txn.len(), 1);
2980         check_spends!(node_txn[0], commitment_tx[0]);
2981         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2982 }
2983
2984 #[test]
2985 fn test_htlc_on_chain_timeout() {
2986         do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
2987         do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
2988         do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
2989 }
2990
2991 #[test]
2992 fn test_simple_commitment_revoked_fail_backward() {
2993         // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
2994         // and fail backward accordingly.
2995
2996         let chanmon_cfgs = create_chanmon_cfgs(3);
2997         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2998         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2999         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3000
3001         // Create some initial channels
3002         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3003         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3004
3005         let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3006         // Get the will-be-revoked local txn from nodes[2]
3007         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3008         // Revoke the old state
3009         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3010
3011         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3012
3013         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3014         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3015         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3016         check_added_monitors!(nodes[1], 1);
3017         check_closed_broadcast!(nodes[1], true);
3018
3019         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 }]);
3020         check_added_monitors!(nodes[1], 1);
3021         let events = nodes[1].node.get_and_clear_pending_msg_events();
3022         assert_eq!(events.len(), 1);
3023         match events[0] {
3024                 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, .. } } => {
3025                         assert!(update_add_htlcs.is_empty());
3026                         assert_eq!(update_fail_htlcs.len(), 1);
3027                         assert!(update_fulfill_htlcs.is_empty());
3028                         assert!(update_fail_malformed_htlcs.is_empty());
3029                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3030
3031                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3032                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3033                         expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3034                 },
3035                 _ => panic!("Unexpected event"),
3036         }
3037 }
3038
3039 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3040         // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3041         // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3042         // commitment transaction anymore.
3043         // To do this, we have the peer which will broadcast a revoked commitment transaction send
3044         // a number of update_fail/commitment_signed updates without ever sending the RAA in
3045         // response to our commitment_signed. This is somewhat misbehavior-y, though not
3046         // technically disallowed and we should probably handle it reasonably.
3047         // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3048         // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3049         // transactions:
3050         // * Once we move it out of our holding cell/add it, we will immediately include it in a
3051         //   commitment_signed (implying it will be in the latest remote commitment transaction).
3052         // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3053         //   and once they revoke the previous commitment transaction (allowing us to send a new
3054         //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3055         let chanmon_cfgs = create_chanmon_cfgs(3);
3056         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3057         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3058         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3059
3060         // Create some initial channels
3061         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3062         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3063
3064         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 });
3065         // Get the will-be-revoked local txn from nodes[2]
3066         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3067         assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3068         // Revoke the old state
3069         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3070
3071         let value = if use_dust {
3072                 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3073                 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3074                 nodes[2].node.per_peer_state.read().unwrap().get(&nodes[1].node.get_our_node_id())
3075                         .unwrap().lock().unwrap().channel_by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3076         } else { 3000000 };
3077
3078         let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3079         let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3080         let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3081
3082         nodes[2].node.fail_htlc_backwards(&first_payment_hash);
3083         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
3084         check_added_monitors!(nodes[2], 1);
3085         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3086         assert!(updates.update_add_htlcs.is_empty());
3087         assert!(updates.update_fulfill_htlcs.is_empty());
3088         assert!(updates.update_fail_malformed_htlcs.is_empty());
3089         assert_eq!(updates.update_fail_htlcs.len(), 1);
3090         assert!(updates.update_fee.is_none());
3091         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3092         let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3093         // Drop the last RAA from 3 -> 2
3094
3095         nodes[2].node.fail_htlc_backwards(&second_payment_hash);
3096         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: second_payment_hash }]);
3097         check_added_monitors!(nodes[2], 1);
3098         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3099         assert!(updates.update_add_htlcs.is_empty());
3100         assert!(updates.update_fulfill_htlcs.is_empty());
3101         assert!(updates.update_fail_malformed_htlcs.is_empty());
3102         assert_eq!(updates.update_fail_htlcs.len(), 1);
3103         assert!(updates.update_fee.is_none());
3104         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3105         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3106         check_added_monitors!(nodes[1], 1);
3107         // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3108         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3109         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3110         check_added_monitors!(nodes[2], 1);
3111
3112         nodes[2].node.fail_htlc_backwards(&third_payment_hash);
3113         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: third_payment_hash }]);
3114         check_added_monitors!(nodes[2], 1);
3115         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3116         assert!(updates.update_add_htlcs.is_empty());
3117         assert!(updates.update_fulfill_htlcs.is_empty());
3118         assert!(updates.update_fail_malformed_htlcs.is_empty());
3119         assert_eq!(updates.update_fail_htlcs.len(), 1);
3120         assert!(updates.update_fee.is_none());
3121         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3122         // At this point first_payment_hash has dropped out of the latest two commitment
3123         // transactions that nodes[1] is tracking...
3124         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3125         check_added_monitors!(nodes[1], 1);
3126         // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3127         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3128         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3129         check_added_monitors!(nodes[2], 1);
3130
3131         // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3132         // on nodes[2]'s RAA.
3133         let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3134         nodes[1].node.send_payment(&route, fourth_payment_hash, &Some(fourth_payment_secret), PaymentId(fourth_payment_hash.0)).unwrap();
3135         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3136         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3137         check_added_monitors!(nodes[1], 0);
3138
3139         if deliver_bs_raa {
3140                 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3141                 // One monitor for the new revocation preimage, no second on as we won't generate a new
3142                 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3143                 check_added_monitors!(nodes[1], 1);
3144                 let events = nodes[1].node.get_and_clear_pending_events();
3145                 assert_eq!(events.len(), 2);
3146                 match events[0] {
3147                         Event::PendingHTLCsForwardable { .. } => { },
3148                         _ => panic!("Unexpected event"),
3149                 };
3150                 match events[1] {
3151                         Event::HTLCHandlingFailed { .. } => { },
3152                         _ => panic!("Unexpected event"),
3153                 }
3154                 // Deliberately don't process the pending fail-back so they all fail back at once after
3155                 // block connection just like the !deliver_bs_raa case
3156         }
3157
3158         let mut failed_htlcs = HashSet::new();
3159         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3160
3161         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3162         check_added_monitors!(nodes[1], 1);
3163         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3164
3165         let events = nodes[1].node.get_and_clear_pending_events();
3166         assert_eq!(events.len(), if deliver_bs_raa { 2 + nodes.len() - 1 } else { 3 + nodes.len() });
3167         match events[0] {
3168                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3169                 _ => panic!("Unexepected event"),
3170         }
3171         match events[1] {
3172                 Event::PaymentPathFailed { ref payment_hash, .. } => {
3173                         assert_eq!(*payment_hash, fourth_payment_hash);
3174                 },
3175                 _ => panic!("Unexpected event"),
3176         }
3177         if !deliver_bs_raa {
3178                 match events[2] {
3179                         Event::PendingHTLCsForwardable { .. } => { },
3180                         _ => panic!("Unexpected event"),
3181                 };
3182                 nodes[1].node.abandon_payment(PaymentId(fourth_payment_hash.0));
3183                 let payment_failed_events = nodes[1].node.get_and_clear_pending_events();
3184                 assert_eq!(payment_failed_events.len(), 1);
3185                 match payment_failed_events[0] {
3186                         Event::PaymentFailed { ref payment_hash, .. } => {
3187                                 assert_eq!(*payment_hash, fourth_payment_hash);
3188                         },
3189                         _ => panic!("Unexpected event"),
3190                 }
3191         }
3192         nodes[1].node.process_pending_htlc_forwards();
3193         check_added_monitors!(nodes[1], 1);
3194
3195         let events = nodes[1].node.get_and_clear_pending_msg_events();
3196         assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3197         match events[if deliver_bs_raa { 1 } else { 0 }] {
3198                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3199                 _ => panic!("Unexpected event"),
3200         }
3201         match events[if deliver_bs_raa { 2 } else { 1 }] {
3202                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3203                         assert_eq!(channel_id, chan_2.2);
3204                         assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3205                 },
3206                 _ => panic!("Unexpected event"),
3207         }
3208         if deliver_bs_raa {
3209                 match events[0] {
3210                         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, .. } } => {
3211                                 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3212                                 assert_eq!(update_add_htlcs.len(), 1);
3213                                 assert!(update_fulfill_htlcs.is_empty());
3214                                 assert!(update_fail_htlcs.is_empty());
3215                                 assert!(update_fail_malformed_htlcs.is_empty());
3216                         },
3217                         _ => panic!("Unexpected event"),
3218                 }
3219         }
3220         match events[if deliver_bs_raa { 3 } else { 2 }] {
3221                 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, .. } } => {
3222                         assert!(update_add_htlcs.is_empty());
3223                         assert_eq!(update_fail_htlcs.len(), 3);
3224                         assert!(update_fulfill_htlcs.is_empty());
3225                         assert!(update_fail_malformed_htlcs.is_empty());
3226                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3227
3228                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3229                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3230                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3231
3232                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3233
3234                         let events = nodes[0].node.get_and_clear_pending_events();
3235                         assert_eq!(events.len(), 3);
3236                         match events[0] {
3237                                 Event::PaymentPathFailed { ref payment_hash, ref network_update, .. } => {
3238                                         assert!(failed_htlcs.insert(payment_hash.0));
3239                                         // If we delivered B's RAA we got an unknown preimage error, not something
3240                                         // that we should update our routing table for.
3241                                         if !deliver_bs_raa {
3242                                                 assert!(network_update.is_some());
3243                                         }
3244                                 },
3245                                 _ => panic!("Unexpected event"),
3246                         }
3247                         match events[1] {
3248                                 Event::PaymentPathFailed { ref payment_hash, ref network_update, .. } => {
3249                                         assert!(failed_htlcs.insert(payment_hash.0));
3250                                         assert!(network_update.is_some());
3251                                 },
3252                                 _ => panic!("Unexpected event"),
3253                         }
3254                         match events[2] {
3255                                 Event::PaymentPathFailed { ref payment_hash, ref network_update, .. } => {
3256                                         assert!(failed_htlcs.insert(payment_hash.0));
3257                                         assert!(network_update.is_some());
3258                                 },
3259                                 _ => panic!("Unexpected event"),
3260                         }
3261                 },
3262                 _ => panic!("Unexpected event"),
3263         }
3264
3265         assert!(failed_htlcs.contains(&first_payment_hash.0));
3266         assert!(failed_htlcs.contains(&second_payment_hash.0));
3267         assert!(failed_htlcs.contains(&third_payment_hash.0));
3268 }
3269
3270 #[test]
3271 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3272         do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3273         do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3274         do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3275         do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3276 }
3277
3278 #[test]
3279 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3280         do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3281         do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3282         do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3283         do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3284 }
3285
3286 #[test]
3287 fn fail_backward_pending_htlc_upon_channel_failure() {
3288         let chanmon_cfgs = create_chanmon_cfgs(2);
3289         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3290         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3291         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3292         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3293
3294         // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3295         {
3296                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3297                 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
3298                 check_added_monitors!(nodes[0], 1);
3299
3300                 let payment_event = {
3301                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3302                         assert_eq!(events.len(), 1);
3303                         SendEvent::from_event(events.remove(0))
3304                 };
3305                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3306                 assert_eq!(payment_event.msgs.len(), 1);
3307         }
3308
3309         // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3310         let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3311         {
3312                 nodes[0].node.send_payment(&route, failed_payment_hash, &Some(failed_payment_secret), PaymentId(failed_payment_hash.0)).unwrap();
3313                 check_added_monitors!(nodes[0], 0);
3314
3315                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3316         }
3317
3318         // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3319         {
3320                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3321
3322                 let secp_ctx = Secp256k1::new();
3323                 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3324                 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3325                 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &Some(payment_secret), current_height, &None).unwrap();
3326                 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3327                 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3328
3329                 // Send a 0-msat update_add_htlc to fail the channel.
3330                 let update_add_htlc = msgs::UpdateAddHTLC {
3331                         channel_id: chan.2,
3332                         htlc_id: 0,
3333                         amount_msat: 0,
3334                         payment_hash,
3335                         cltv_expiry,
3336                         onion_routing_packet,
3337                 };
3338                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3339         }
3340         let events = nodes[0].node.get_and_clear_pending_events();
3341         assert_eq!(events.len(), 2);
3342         // Check that Alice fails backward the pending HTLC from the second payment.
3343         match events[0] {
3344                 Event::PaymentPathFailed { payment_hash, .. } => {
3345                         assert_eq!(payment_hash, failed_payment_hash);
3346                 },
3347                 _ => panic!("Unexpected event"),
3348         }
3349         match events[1] {
3350                 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3351                         assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3352                 },
3353                 _ => panic!("Unexpected event {:?}", events[1]),
3354         }
3355         check_closed_broadcast!(nodes[0], true);
3356         check_added_monitors!(nodes[0], 1);
3357 }
3358
3359 #[test]
3360 fn test_htlc_ignore_latest_remote_commitment() {
3361         // Test that HTLC transactions spending the latest remote commitment transaction are simply
3362         // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3363         let chanmon_cfgs = create_chanmon_cfgs(2);
3364         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3365         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3366         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3367         if *nodes[1].connect_style.borrow() == ConnectStyle::FullBlockViaListen {
3368                 // We rely on the ability to connect a block redundantly, which isn't allowed via
3369                 // `chain::Listen`, so we never run the test if we randomly get assigned that
3370                 // connect_style.
3371                 return;
3372         }
3373         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3374
3375         route_payment(&nodes[0], &[&nodes[1]], 10000000);
3376         nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3377         connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3378         check_closed_broadcast!(nodes[0], true);
3379         check_added_monitors!(nodes[0], 1);
3380         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
3381
3382         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3383         assert_eq!(node_txn.len(), 3);
3384         assert_eq!(node_txn[0], node_txn[1]);
3385
3386         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
3387         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3388         check_closed_broadcast!(nodes[1], true);
3389         check_added_monitors!(nodes[1], 1);
3390         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3391
3392         // Duplicate the connect_block call since this may happen due to other listeners
3393         // registering new transactions
3394         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[2].clone()]});
3395 }
3396
3397 #[test]
3398 fn test_force_close_fail_back() {
3399         // Check which HTLCs are failed-backwards on channel force-closure
3400         let chanmon_cfgs = create_chanmon_cfgs(3);
3401         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3402         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3403         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3404         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3405         create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3406
3407         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3408
3409         let mut payment_event = {
3410                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
3411                 check_added_monitors!(nodes[0], 1);
3412
3413                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3414                 assert_eq!(events.len(), 1);
3415                 SendEvent::from_event(events.remove(0))
3416         };
3417
3418         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3419         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3420
3421         expect_pending_htlcs_forwardable!(nodes[1]);
3422
3423         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3424         assert_eq!(events_2.len(), 1);
3425         payment_event = SendEvent::from_event(events_2.remove(0));
3426         assert_eq!(payment_event.msgs.len(), 1);
3427
3428         check_added_monitors!(nodes[1], 1);
3429         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3430         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3431         check_added_monitors!(nodes[2], 1);
3432         let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3433
3434         // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3435         // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3436         // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3437
3438         nodes[2].node.force_close_broadcasting_latest_txn(&payment_event.commitment_msg.channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3439         check_closed_broadcast!(nodes[2], true);
3440         check_added_monitors!(nodes[2], 1);
3441         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
3442         let tx = {
3443                 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3444                 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3445                 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3446                 // back to nodes[1] upon timeout otherwise.
3447                 assert_eq!(node_txn.len(), 1);
3448                 node_txn.remove(0)
3449         };
3450
3451         mine_transaction(&nodes[1], &tx);
3452
3453         // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3454         check_closed_broadcast!(nodes[1], true);
3455         check_added_monitors!(nodes[1], 1);
3456         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3457
3458         // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3459         {
3460                 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3461                         .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);
3462         }
3463         mine_transaction(&nodes[2], &tx);
3464         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3465         assert_eq!(node_txn.len(), 1);
3466         assert_eq!(node_txn[0].input.len(), 1);
3467         assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3468         assert_eq!(node_txn[0].lock_time.0, 0); // Must be an HTLC-Success
3469         assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3470
3471         check_spends!(node_txn[0], tx);
3472 }
3473
3474 #[test]
3475 fn test_dup_events_on_peer_disconnect() {
3476         // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3477         // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3478         // as we used to generate the event immediately upon receipt of the payment preimage in the
3479         // update_fulfill_htlc message.
3480
3481         let chanmon_cfgs = create_chanmon_cfgs(2);
3482         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3483         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3484         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3485         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3486
3487         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3488
3489         nodes[1].node.claim_funds(payment_preimage);
3490         expect_payment_claimed!(nodes[1], payment_hash, 1_000_000);
3491         check_added_monitors!(nodes[1], 1);
3492         let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3493         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3494         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
3495
3496         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3497         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3498
3499         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3500         expect_payment_path_successful!(nodes[0]);
3501 }
3502
3503 #[test]
3504 fn test_peer_disconnected_before_funding_broadcasted() {
3505         // Test that channels are closed with `ClosureReason::DisconnectedPeer` if the peer disconnects
3506         // before the funding transaction has been broadcasted.
3507         let chanmon_cfgs = create_chanmon_cfgs(2);
3508         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3509         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3510         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3511
3512         // Open a channel between `nodes[0]` and `nodes[1]`, for which the funding transaction is never
3513         // broadcasted, even though it's created by `nodes[0]`.
3514         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();
3515         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
3516         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_channel);
3517         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
3518         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_channel);
3519
3520         let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
3521         assert_eq!(temporary_channel_id, expected_temporary_channel_id);
3522
3523         assert!(nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
3524
3525         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
3526         assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
3527
3528         // Even though the funding transaction is created by `nodes[0]`, the `FundingCreated` msg is
3529         // never sent to `nodes[1]`, and therefore the tx is never signed by either party nor
3530         // broadcasted.
3531         {
3532                 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
3533         }
3534
3535         // Ensure that the channel is closed with `ClosureReason::DisconnectedPeer` when the peers are
3536         // disconnected before the funding transaction was broadcasted.
3537         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3538         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3539
3540         check_closed_event!(nodes[0], 1, ClosureReason::DisconnectedPeer);
3541         check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
3542 }
3543
3544 #[test]
3545 fn test_simple_peer_disconnect() {
3546         // Test that we can reconnect when there are no lost messages
3547         let chanmon_cfgs = create_chanmon_cfgs(3);
3548         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3549         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3550         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3551         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3552         create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3553
3554         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3555         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3556         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3557
3558         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3559         let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3560         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3561         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3562
3563         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3564         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3565         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3566
3567         let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3568         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3569         let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3570         let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3571
3572         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3573         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3574
3575         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3576         fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3577
3578         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3579         {
3580                 let events = nodes[0].node.get_and_clear_pending_events();
3581                 assert_eq!(events.len(), 3);
3582                 match events[0] {
3583                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3584                                 assert_eq!(payment_preimage, payment_preimage_3);
3585                                 assert_eq!(payment_hash, payment_hash_3);
3586                         },
3587                         _ => panic!("Unexpected event"),
3588                 }
3589                 match events[1] {
3590                         Event::PaymentPathFailed { payment_hash, payment_failed_permanently, .. } => {
3591                                 assert_eq!(payment_hash, payment_hash_5);
3592                                 assert!(payment_failed_permanently);
3593                         },
3594                         _ => panic!("Unexpected event"),
3595                 }
3596                 match events[2] {
3597                         Event::PaymentPathSuccessful { .. } => {},
3598                         _ => panic!("Unexpected event"),
3599                 }
3600         }
3601
3602         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3603         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3604 }
3605
3606 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3607         // Test that we can reconnect when in-flight HTLC updates get dropped
3608         let chanmon_cfgs = create_chanmon_cfgs(2);
3609         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3610         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3611         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3612
3613         let mut as_channel_ready = None;
3614         let channel_id = if messages_delivered == 0 {
3615                 let (channel_ready, chan_id, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3616                 as_channel_ready = Some(channel_ready);
3617                 // nodes[1] doesn't receive the channel_ready message (it'll be re-sent on reconnect)
3618                 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3619                 // it before the channel_reestablish message.
3620                 chan_id
3621         } else {
3622                 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2
3623         };
3624
3625         let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1_000_000);
3626
3627         let payment_event = {
3628                 nodes[0].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
3629                 check_added_monitors!(nodes[0], 1);
3630
3631                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3632                 assert_eq!(events.len(), 1);
3633                 SendEvent::from_event(events.remove(0))
3634         };
3635         assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3636
3637         if messages_delivered < 2 {
3638                 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3639         } else {
3640                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3641                 if messages_delivered >= 3 {
3642                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3643                         check_added_monitors!(nodes[1], 1);
3644                         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3645
3646                         if messages_delivered >= 4 {
3647                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3648                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3649                                 check_added_monitors!(nodes[0], 1);
3650
3651                                 if messages_delivered >= 5 {
3652                                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3653                                         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3654                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3655                                         check_added_monitors!(nodes[0], 1);
3656
3657                                         if messages_delivered >= 6 {
3658                                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3659                                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3660                                                 check_added_monitors!(nodes[1], 1);
3661                                         }
3662                                 }
3663                         }
3664                 }
3665         }
3666
3667         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3668         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3669         if messages_delivered < 3 {
3670                 if simulate_broken_lnd {
3671                         // lnd has a long-standing bug where they send a channel_ready prior to a
3672                         // channel_reestablish if you reconnect prior to channel_ready time.
3673                         //
3674                         // Here we simulate that behavior, delivering a channel_ready immediately on
3675                         // reconnect. Note that we don't bother skipping the now-duplicate channel_ready sent
3676                         // in `reconnect_nodes` but we currently don't fail based on that.
3677                         //
3678                         // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3679                         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready.as_ref().unwrap().0);
3680                 }
3681                 // Even if the channel_ready messages get exchanged, as long as nothing further was
3682                 // received on either side, both sides will need to resend them.
3683                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3684         } else if messages_delivered == 3 {
3685                 // nodes[0] still wants its RAA + commitment_signed
3686                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3687         } else if messages_delivered == 4 {
3688                 // nodes[0] still wants its commitment_signed
3689                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3690         } else if messages_delivered == 5 {
3691                 // nodes[1] still wants its final RAA
3692                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3693         } else if messages_delivered == 6 {
3694                 // Everything was delivered...
3695                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3696         }
3697
3698         let events_1 = nodes[1].node.get_and_clear_pending_events();
3699         if messages_delivered == 0 {
3700                 assert_eq!(events_1.len(), 2);
3701                 match events_1[0] {
3702                         Event::ChannelReady { .. } => { },
3703                         _ => panic!("Unexpected event"),
3704                 };
3705                 match events_1[1] {
3706                         Event::PendingHTLCsForwardable { .. } => { },
3707                         _ => panic!("Unexpected event"),
3708                 };
3709         } else {
3710                 assert_eq!(events_1.len(), 1);
3711                 match events_1[0] {
3712                         Event::PendingHTLCsForwardable { .. } => { },
3713                         _ => panic!("Unexpected event"),
3714                 };
3715         }
3716
3717         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3718         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3719         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3720
3721         nodes[1].node.process_pending_htlc_forwards();
3722
3723         let events_2 = nodes[1].node.get_and_clear_pending_events();
3724         assert_eq!(events_2.len(), 1);
3725         match events_2[0] {
3726                 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, via_user_channel_id: _ } => {
3727                         assert_eq!(payment_hash_1, *payment_hash);
3728                         assert_eq!(amount_msat, 1_000_000);
3729                         assert_eq!(receiver_node_id.unwrap(), nodes[1].node.get_our_node_id());
3730                         assert_eq!(via_channel_id, Some(channel_id));
3731                         match &purpose {
3732                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3733                                         assert!(payment_preimage.is_none());
3734                                         assert_eq!(payment_secret_1, *payment_secret);
3735                                 },
3736                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
3737                         }
3738                 },
3739                 _ => panic!("Unexpected event"),
3740         }
3741
3742         nodes[1].node.claim_funds(payment_preimage_1);
3743         check_added_monitors!(nodes[1], 1);
3744         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3745
3746         let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3747         assert_eq!(events_3.len(), 1);
3748         let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3749                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3750                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3751                         assert!(updates.update_add_htlcs.is_empty());
3752                         assert!(updates.update_fail_htlcs.is_empty());
3753                         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3754                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3755                         assert!(updates.update_fee.is_none());
3756                         (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3757                 },
3758                 _ => panic!("Unexpected event"),
3759         };
3760
3761         if messages_delivered >= 1 {
3762                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3763
3764                 let events_4 = nodes[0].node.get_and_clear_pending_events();
3765                 assert_eq!(events_4.len(), 1);
3766                 match events_4[0] {
3767                         Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3768                                 assert_eq!(payment_preimage_1, *payment_preimage);
3769                                 assert_eq!(payment_hash_1, *payment_hash);
3770                         },
3771                         _ => panic!("Unexpected event"),
3772                 }
3773
3774                 if messages_delivered >= 2 {
3775                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3776                         check_added_monitors!(nodes[0], 1);
3777                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3778
3779                         if messages_delivered >= 3 {
3780                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3781                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3782                                 check_added_monitors!(nodes[1], 1);
3783
3784                                 if messages_delivered >= 4 {
3785                                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3786                                         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3787                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3788                                         check_added_monitors!(nodes[1], 1);
3789
3790                                         if messages_delivered >= 5 {
3791                                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3792                                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3793                                                 check_added_monitors!(nodes[0], 1);
3794                                         }
3795                                 }
3796                         }
3797                 }
3798         }
3799
3800         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3801         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3802         if messages_delivered < 2 {
3803                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3804                 if messages_delivered < 1 {
3805                         expect_payment_sent!(nodes[0], payment_preimage_1);
3806                 } else {
3807                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3808                 }
3809         } else if messages_delivered == 2 {
3810                 // nodes[0] still wants its RAA + commitment_signed
3811                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3812         } else if messages_delivered == 3 {
3813                 // nodes[0] still wants its commitment_signed
3814                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3815         } else if messages_delivered == 4 {
3816                 // nodes[1] still wants its final RAA
3817                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3818         } else if messages_delivered == 5 {
3819                 // Everything was delivered...
3820                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3821         }
3822
3823         if messages_delivered == 1 || messages_delivered == 2 {
3824                 expect_payment_path_successful!(nodes[0]);
3825         }
3826
3827         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3828         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3829         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3830
3831         if messages_delivered > 2 {
3832                 expect_payment_path_successful!(nodes[0]);
3833         }
3834
3835         // Channel should still work fine...
3836         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3837         let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3838         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3839 }
3840
3841 #[test]
3842 fn test_drop_messages_peer_disconnect_a() {
3843         do_test_drop_messages_peer_disconnect(0, true);
3844         do_test_drop_messages_peer_disconnect(0, false);
3845         do_test_drop_messages_peer_disconnect(1, false);
3846         do_test_drop_messages_peer_disconnect(2, false);
3847 }
3848
3849 #[test]
3850 fn test_drop_messages_peer_disconnect_b() {
3851         do_test_drop_messages_peer_disconnect(3, false);
3852         do_test_drop_messages_peer_disconnect(4, false);
3853         do_test_drop_messages_peer_disconnect(5, false);
3854         do_test_drop_messages_peer_disconnect(6, false);
3855 }
3856
3857 #[test]
3858 fn test_channel_ready_without_best_block_updated() {
3859         // Previously, if we were offline when a funding transaction was locked in, and then we came
3860         // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
3861         // generate a channel_ready until a later best_block_updated. This tests that we generate the
3862         // channel_ready immediately instead.
3863         let chanmon_cfgs = create_chanmon_cfgs(2);
3864         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3865         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3866         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3867         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
3868
3869         let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3870
3871         let conf_height = nodes[0].best_block_info().1 + 1;
3872         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
3873         let block_txn = [funding_tx];
3874         let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
3875         let conf_block_header = nodes[0].get_block_header(conf_height);
3876         nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
3877
3878         // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
3879         let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
3880         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
3881 }
3882
3883 #[test]
3884 fn test_drop_messages_peer_disconnect_dual_htlc() {
3885         // Test that we can handle reconnecting when both sides of a channel have pending
3886         // commitment_updates when we disconnect.
3887         let chanmon_cfgs = create_chanmon_cfgs(2);
3888         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3889         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3890         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3891         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3892
3893         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3894
3895         // Now try to send a second payment which will fail to send
3896         let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3897         nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
3898         check_added_monitors!(nodes[0], 1);
3899
3900         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3901         assert_eq!(events_1.len(), 1);
3902         match events_1[0] {
3903                 MessageSendEvent::UpdateHTLCs { .. } => {},
3904                 _ => panic!("Unexpected event"),
3905         }
3906
3907         nodes[1].node.claim_funds(payment_preimage_1);
3908         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3909         check_added_monitors!(nodes[1], 1);
3910
3911         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3912         assert_eq!(events_2.len(), 1);
3913         match events_2[0] {
3914                 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 } } => {
3915                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3916                         assert!(update_add_htlcs.is_empty());
3917                         assert_eq!(update_fulfill_htlcs.len(), 1);
3918                         assert!(update_fail_htlcs.is_empty());
3919                         assert!(update_fail_malformed_htlcs.is_empty());
3920                         assert!(update_fee.is_none());
3921
3922                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
3923                         let events_3 = nodes[0].node.get_and_clear_pending_events();
3924                         assert_eq!(events_3.len(), 1);
3925                         match events_3[0] {
3926                                 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3927                                         assert_eq!(*payment_preimage, payment_preimage_1);
3928                                         assert_eq!(*payment_hash, payment_hash_1);
3929                                 },
3930                                 _ => panic!("Unexpected event"),
3931                         }
3932
3933                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
3934                         let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3935                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3936                         check_added_monitors!(nodes[0], 1);
3937                 },
3938                 _ => panic!("Unexpected event"),
3939         }
3940
3941         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3942         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3943
3944         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
3945         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3946         assert_eq!(reestablish_1.len(), 1);
3947         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
3948         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3949         assert_eq!(reestablish_2.len(), 1);
3950
3951         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
3952         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
3953         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
3954         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
3955
3956         assert!(as_resp.0.is_none());
3957         assert!(bs_resp.0.is_none());
3958
3959         assert!(bs_resp.1.is_none());
3960         assert!(bs_resp.2.is_none());
3961
3962         assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
3963
3964         assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
3965         assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
3966         assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
3967         assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
3968         assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
3969         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
3970         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
3971         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3972         // No commitment_signed so get_event_msg's assert(len == 1) passes
3973         check_added_monitors!(nodes[1], 1);
3974
3975         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
3976         let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3977         assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
3978         assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
3979         assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
3980         assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
3981         assert!(bs_second_commitment_signed.update_fee.is_none());
3982         check_added_monitors!(nodes[1], 1);
3983
3984         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3985         let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3986         assert!(as_commitment_signed.update_add_htlcs.is_empty());
3987         assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
3988         assert!(as_commitment_signed.update_fail_htlcs.is_empty());
3989         assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
3990         assert!(as_commitment_signed.update_fee.is_none());
3991         check_added_monitors!(nodes[0], 1);
3992
3993         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
3994         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3995         // No commitment_signed so get_event_msg's assert(len == 1) passes
3996         check_added_monitors!(nodes[0], 1);
3997
3998         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
3999         let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4000         // No commitment_signed so get_event_msg's assert(len == 1) passes
4001         check_added_monitors!(nodes[1], 1);
4002
4003         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4004         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4005         check_added_monitors!(nodes[1], 1);
4006
4007         expect_pending_htlcs_forwardable!(nodes[1]);
4008
4009         let events_5 = nodes[1].node.get_and_clear_pending_events();
4010         assert_eq!(events_5.len(), 1);
4011         match events_5[0] {
4012                 Event::PaymentClaimable { ref payment_hash, ref purpose, .. } => {
4013                         assert_eq!(payment_hash_2, *payment_hash);
4014                         match &purpose {
4015                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4016                                         assert!(payment_preimage.is_none());
4017                                         assert_eq!(payment_secret_2, *payment_secret);
4018                                 },
4019                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
4020                         }
4021                 },
4022                 _ => panic!("Unexpected event"),
4023         }
4024
4025         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4026         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4027         check_added_monitors!(nodes[0], 1);
4028
4029         expect_payment_path_successful!(nodes[0]);
4030         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4031 }
4032
4033 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4034         // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4035         // to avoid our counterparty failing the channel.
4036         let chanmon_cfgs = create_chanmon_cfgs(2);
4037         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4038         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4039         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4040
4041         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4042
4043         let our_payment_hash = if send_partial_mpp {
4044                 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4045                 // Use the utility function send_payment_along_path to send the payment with MPP data which
4046                 // indicates there are more HTLCs coming.
4047                 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.
4048                 let payment_id = PaymentId([42; 32]);
4049                 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash, Some(payment_secret), payment_id, &route).unwrap();
4050                 nodes[0].node.send_payment_along_path(&route.paths[0], &route.payment_params, &our_payment_hash, &Some(payment_secret), 200_000, cur_height, payment_id, &None, session_privs[0]).unwrap();
4051                 check_added_monitors!(nodes[0], 1);
4052                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4053                 assert_eq!(events.len(), 1);
4054                 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4055                 // hop should *not* yet generate any PaymentClaimable event(s).
4056                 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4057                 our_payment_hash
4058         } else {
4059                 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4060         };
4061
4062         let mut block = Block {
4063                 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
4064                 txdata: vec![],
4065         };
4066         connect_block(&nodes[0], &block);
4067         connect_block(&nodes[1], &block);
4068         let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4069         for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4070                 block.header.prev_blockhash = block.block_hash();
4071                 connect_block(&nodes[0], &block);
4072                 connect_block(&nodes[1], &block);
4073         }
4074
4075         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
4076
4077         check_added_monitors!(nodes[1], 1);
4078         let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4079         assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4080         assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4081         assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4082         assert!(htlc_timeout_updates.update_fee.is_none());
4083
4084         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4085         commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4086         // 100_000 msat as u64, followed by the height at which we failed back above
4087         let mut expected_failure_data = (100_000 as u64).to_be_bytes().to_vec();
4088         expected_failure_data.extend_from_slice(&(block_count - 1).to_be_bytes());
4089         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4090 }
4091
4092 #[test]
4093 fn test_htlc_timeout() {
4094         do_test_htlc_timeout(true);
4095         do_test_htlc_timeout(false);
4096 }
4097
4098 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4099         // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4100         let chanmon_cfgs = create_chanmon_cfgs(3);
4101         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4102         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4103         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4104         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4105         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4106
4107         // Make sure all nodes are at the same starting height
4108         connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4109         connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4110         connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4111
4112         // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4113         let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4114         {
4115                 nodes[1].node.send_payment(&route, first_payment_hash, &Some(first_payment_secret), PaymentId(first_payment_hash.0)).unwrap();
4116         }
4117         assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4118         check_added_monitors!(nodes[1], 1);
4119
4120         // Now attempt to route a second payment, which should be placed in the holding cell
4121         let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4122         let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4123         sending_node.node.send_payment(&route, second_payment_hash, &Some(second_payment_secret), PaymentId(second_payment_hash.0)).unwrap();
4124         if forwarded_htlc {
4125                 check_added_monitors!(nodes[0], 1);
4126                 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4127                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4128                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4129                 expect_pending_htlcs_forwardable!(nodes[1]);
4130         }
4131         check_added_monitors!(nodes[1], 0);
4132
4133         connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4134         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4135         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4136         connect_blocks(&nodes[1], 1);
4137
4138         if forwarded_htlc {
4139                 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 }]);
4140                 check_added_monitors!(nodes[1], 1);
4141                 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4142                 assert_eq!(fail_commit.len(), 1);
4143                 match fail_commit[0] {
4144                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4145                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4146                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4147                         },
4148                         _ => unreachable!(),
4149                 }
4150                 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4151         } else {
4152                 expect_payment_failed!(nodes[1], second_payment_hash, false);
4153         }
4154 }
4155
4156 #[test]
4157 fn test_holding_cell_htlc_add_timeouts() {
4158         do_test_holding_cell_htlc_add_timeouts(false);
4159         do_test_holding_cell_htlc_add_timeouts(true);
4160 }
4161
4162 macro_rules! check_spendable_outputs {
4163         ($node: expr, $keysinterface: expr) => {
4164                 {
4165                         let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4166                         let mut txn = Vec::new();
4167                         let mut all_outputs = Vec::new();
4168                         let secp_ctx = Secp256k1::new();
4169                         for event in events.drain(..) {
4170                                 match event {
4171                                         Event::SpendableOutputs { mut outputs } => {
4172                                                 for outp in outputs.drain(..) {
4173                                                         txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4174                                                         all_outputs.push(outp);
4175                                                 }
4176                                         },
4177                                         _ => panic!("Unexpected event"),
4178                                 };
4179                         }
4180                         if all_outputs.len() > 1 {
4181                                 if let Ok(tx) = $keysinterface.backing.spend_spendable_outputs(&all_outputs.iter().map(|a| a).collect::<Vec<_>>(), Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx) {
4182                                         txn.push(tx);
4183                                 }
4184                         }
4185                         txn
4186                 }
4187         }
4188 }
4189
4190 #[test]
4191 fn test_claim_sizeable_push_msat() {
4192         // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4193         let chanmon_cfgs = create_chanmon_cfgs(2);
4194         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4195         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4196         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4197
4198         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4199         nodes[1].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
4200         check_closed_broadcast!(nodes[1], true);
4201         check_added_monitors!(nodes[1], 1);
4202         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4203         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4204         assert_eq!(node_txn.len(), 1);
4205         check_spends!(node_txn[0], chan.3);
4206         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
4207
4208         mine_transaction(&nodes[1], &node_txn[0]);
4209         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4210
4211         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4212         assert_eq!(spend_txn.len(), 1);
4213         assert_eq!(spend_txn[0].input.len(), 1);
4214         check_spends!(spend_txn[0], node_txn[0]);
4215         assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4216 }
4217
4218 #[test]
4219 fn test_claim_on_remote_sizeable_push_msat() {
4220         // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4221         // to_remote output is encumbered by a P2WPKH
4222         let chanmon_cfgs = create_chanmon_cfgs(2);
4223         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4224         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4225         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4226
4227         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4228         nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
4229         check_closed_broadcast!(nodes[0], true);
4230         check_added_monitors!(nodes[0], 1);
4231         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4232
4233         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4234         assert_eq!(node_txn.len(), 1);
4235         check_spends!(node_txn[0], chan.3);
4236         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
4237
4238         mine_transaction(&nodes[1], &node_txn[0]);
4239         check_closed_broadcast!(nodes[1], true);
4240         check_added_monitors!(nodes[1], 1);
4241         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4242         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4243
4244         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4245         assert_eq!(spend_txn.len(), 1);
4246         check_spends!(spend_txn[0], node_txn[0]);
4247 }
4248
4249 #[test]
4250 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4251         // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4252         // to_remote output is encumbered by a P2WPKH
4253
4254         let chanmon_cfgs = create_chanmon_cfgs(2);
4255         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4256         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4257         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4258
4259         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4260         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4261         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4262         assert_eq!(revoked_local_txn[0].input.len(), 1);
4263         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4264
4265         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4266         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4267         check_closed_broadcast!(nodes[1], true);
4268         check_added_monitors!(nodes[1], 1);
4269         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4270
4271         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4272         mine_transaction(&nodes[1], &node_txn[0]);
4273         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4274
4275         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4276         assert_eq!(spend_txn.len(), 3);
4277         check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4278         check_spends!(spend_txn[1], node_txn[0]);
4279         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4280 }
4281
4282 #[test]
4283 fn test_static_spendable_outputs_preimage_tx() {
4284         let chanmon_cfgs = create_chanmon_cfgs(2);
4285         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4286         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4287         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4288
4289         // Create some initial channels
4290         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4291
4292         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
4293
4294         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4295         assert_eq!(commitment_tx[0].input.len(), 1);
4296         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4297
4298         // Settle A's commitment tx on B's chain
4299         nodes[1].node.claim_funds(payment_preimage);
4300         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
4301         check_added_monitors!(nodes[1], 1);
4302         mine_transaction(&nodes[1], &commitment_tx[0]);
4303         check_added_monitors!(nodes[1], 1);
4304         let events = nodes[1].node.get_and_clear_pending_msg_events();
4305         match events[0] {
4306                 MessageSendEvent::UpdateHTLCs { .. } => {},
4307                 _ => panic!("Unexpected event"),
4308         }
4309         match events[1] {
4310                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4311                 _ => panic!("Unexepected event"),
4312         }
4313
4314         // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4315         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: preimage tx
4316         assert_eq!(node_txn.len(), 1);
4317         check_spends!(node_txn[0], commitment_tx[0]);
4318         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4319
4320         mine_transaction(&nodes[1], &node_txn[0]);
4321         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4322         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4323
4324         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4325         assert_eq!(spend_txn.len(), 1);
4326         check_spends!(spend_txn[0], node_txn[0]);
4327 }
4328
4329 #[test]
4330 fn test_static_spendable_outputs_timeout_tx() {
4331         let chanmon_cfgs = create_chanmon_cfgs(2);
4332         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4333         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4334         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4335
4336         // Create some initial channels
4337         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4338
4339         // Rebalance the network a bit by relaying one payment through all the channels ...
4340         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4341
4342         let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4343
4344         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4345         assert_eq!(commitment_tx[0].input.len(), 1);
4346         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4347
4348         // Settle A's commitment tx on B' chain
4349         mine_transaction(&nodes[1], &commitment_tx[0]);
4350         check_added_monitors!(nodes[1], 1);
4351         let events = nodes[1].node.get_and_clear_pending_msg_events();
4352         match events[0] {
4353                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4354                 _ => panic!("Unexpected event"),
4355         }
4356         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4357
4358         // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4359         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4360         assert_eq!(node_txn.len(), 1); // ChannelMonitor: timeout tx
4361         check_spends!(node_txn[0],  commitment_tx[0].clone());
4362         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4363
4364         mine_transaction(&nodes[1], &node_txn[0]);
4365         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4366         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4367         expect_payment_failed!(nodes[1], our_payment_hash, false);
4368
4369         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4370         assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4371         check_spends!(spend_txn[0], commitment_tx[0]);
4372         check_spends!(spend_txn[1], node_txn[0]);
4373         check_spends!(spend_txn[2], node_txn[0], commitment_tx[0]); // All outputs
4374 }
4375
4376 #[test]
4377 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4378         let chanmon_cfgs = create_chanmon_cfgs(2);
4379         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4380         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4381         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4382
4383         // Create some initial channels
4384         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4385
4386         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4387         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4388         assert_eq!(revoked_local_txn[0].input.len(), 1);
4389         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4390
4391         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4392
4393         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4394         check_closed_broadcast!(nodes[1], true);
4395         check_added_monitors!(nodes[1], 1);
4396         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4397
4398         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4399         assert_eq!(node_txn.len(), 1);
4400         assert_eq!(node_txn[0].input.len(), 2);
4401         check_spends!(node_txn[0], revoked_local_txn[0]);
4402
4403         mine_transaction(&nodes[1], &node_txn[0]);
4404         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4405
4406         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4407         assert_eq!(spend_txn.len(), 1);
4408         check_spends!(spend_txn[0], node_txn[0]);
4409 }
4410
4411 #[test]
4412 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4413         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4414         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4415         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4416         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4417         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4418
4419         // Create some initial channels
4420         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4421
4422         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4423         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4424         assert_eq!(revoked_local_txn[0].input.len(), 1);
4425         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4426
4427         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4428
4429         // A will generate HTLC-Timeout from revoked commitment tx
4430         mine_transaction(&nodes[0], &revoked_local_txn[0]);
4431         check_closed_broadcast!(nodes[0], true);
4432         check_added_monitors!(nodes[0], 1);
4433         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4434         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4435
4436         let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4437         assert_eq!(revoked_htlc_txn.len(), 1);
4438         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4439         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4440         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4441         assert_ne!(revoked_htlc_txn[0].lock_time.0, 0); // HTLC-Timeout
4442
4443         // B will generate justice tx from A's revoked commitment/HTLC tx
4444         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
4445         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
4446         check_closed_broadcast!(nodes[1], true);
4447         check_added_monitors!(nodes[1], 1);
4448         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4449
4450         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4451         assert_eq!(node_txn.len(), 2); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs
4452         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4453         // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
4454         // transactions next...
4455         assert_eq!(node_txn[0].input.len(), 3);
4456         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4457
4458         assert_eq!(node_txn[1].input.len(), 2);
4459         check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[0]);
4460         if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4461                 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4462         } else {
4463                 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4464                 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4465         }
4466
4467         mine_transaction(&nodes[1], &node_txn[1]);
4468         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4469
4470         // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4471         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4472         assert_eq!(spend_txn.len(), 1);
4473         assert_eq!(spend_txn[0].input.len(), 1);
4474         check_spends!(spend_txn[0], node_txn[1]);
4475 }
4476
4477 #[test]
4478 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4479         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4480         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4481         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4482         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4483         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4484
4485         // Create some initial channels
4486         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4487
4488         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4489         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4490         assert_eq!(revoked_local_txn[0].input.len(), 1);
4491         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4492
4493         // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4494         assert_eq!(revoked_local_txn[0].output.len(), 2);
4495
4496         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4497
4498         // B will generate HTLC-Success from revoked commitment tx
4499         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4500         check_closed_broadcast!(nodes[1], true);
4501         check_added_monitors!(nodes[1], 1);
4502         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4503         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4504
4505         assert_eq!(revoked_htlc_txn.len(), 1);
4506         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4507         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4508         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4509
4510         // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
4511         let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
4512         assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
4513
4514         // A will generate justice tx from B's revoked commitment/HTLC tx
4515         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
4516         connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
4517         check_closed_broadcast!(nodes[0], true);
4518         check_added_monitors!(nodes[0], 1);
4519         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4520
4521         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4522         assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success
4523
4524         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4525         // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4526         // transactions next...
4527         assert_eq!(node_txn[0].input.len(), 2);
4528         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4529         if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4530                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4531         } else {
4532                 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4533                 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4534         }
4535
4536         assert_eq!(node_txn[1].input.len(), 1);
4537         check_spends!(node_txn[1], revoked_htlc_txn[0]);
4538
4539         mine_transaction(&nodes[0], &node_txn[1]);
4540         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
4541
4542         // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
4543         // didn't try to generate any new transactions.
4544
4545         // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4546         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
4547         assert_eq!(spend_txn.len(), 3);
4548         assert_eq!(spend_txn[0].input.len(), 1);
4549         check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
4550         assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4551         check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
4552         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
4553 }
4554
4555 #[test]
4556 fn test_onchain_to_onchain_claim() {
4557         // Test that in case of channel closure, we detect the state of output and claim HTLC
4558         // on downstream peer's remote commitment tx.
4559         // First, have C claim an HTLC against its own latest commitment transaction.
4560         // Then, broadcast these to B, which should update the monitor downstream on the A<->B
4561         // channel.
4562         // Finally, check that B will claim the HTLC output if A's latest commitment transaction
4563         // gets broadcast.
4564
4565         let chanmon_cfgs = create_chanmon_cfgs(3);
4566         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4567         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4568         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4569
4570         // Create some initial channels
4571         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4572         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4573
4574         // Ensure all nodes are at the same height
4575         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4576         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4577         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4578         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4579
4580         // Rebalance the network a bit by relaying one payment through all the channels ...
4581         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4582         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4583
4584         let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
4585         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
4586         check_spends!(commitment_tx[0], chan_2.3);
4587         nodes[2].node.claim_funds(payment_preimage);
4588         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
4589         check_added_monitors!(nodes[2], 1);
4590         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4591         assert!(updates.update_add_htlcs.is_empty());
4592         assert!(updates.update_fail_htlcs.is_empty());
4593         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4594         assert!(updates.update_fail_malformed_htlcs.is_empty());
4595
4596         mine_transaction(&nodes[2], &commitment_tx[0]);
4597         check_closed_broadcast!(nodes[2], true);
4598         check_added_monitors!(nodes[2], 1);
4599         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
4600
4601         let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 1 (HTLC-Success tx)
4602         assert_eq!(c_txn.len(), 1);
4603         check_spends!(c_txn[0], commitment_tx[0]);
4604         assert_eq!(c_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4605         assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4606         assert_eq!(c_txn[0].lock_time.0, 0); // Success tx
4607
4608         // 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
4609         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
4610         connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone(), c_txn[0].clone()]});
4611         check_added_monitors!(nodes[1], 1);
4612         let events = nodes[1].node.get_and_clear_pending_events();
4613         assert_eq!(events.len(), 2);
4614         match events[0] {
4615                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
4616                 _ => panic!("Unexpected event"),
4617         }
4618         match events[1] {
4619                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
4620                         assert_eq!(fee_earned_msat, Some(1000));
4621                         assert_eq!(prev_channel_id, Some(chan_1.2));
4622                         assert_eq!(claim_from_onchain_tx, true);
4623                         assert_eq!(next_channel_id, Some(chan_2.2));
4624                 },
4625                 _ => panic!("Unexpected event"),
4626         }
4627         check_added_monitors!(nodes[1], 1);
4628         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4629         assert_eq!(msg_events.len(), 3);
4630         match msg_events[0] {
4631                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4632                 _ => panic!("Unexpected event"),
4633         }
4634         match msg_events[1] {
4635                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
4636                 _ => panic!("Unexpected event"),
4637         }
4638         match msg_events[2] {
4639                 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, .. } } => {
4640                         assert!(update_add_htlcs.is_empty());
4641                         assert!(update_fail_htlcs.is_empty());
4642                         assert_eq!(update_fulfill_htlcs.len(), 1);
4643                         assert!(update_fail_malformed_htlcs.is_empty());
4644                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
4645                 },
4646                 _ => panic!("Unexpected event"),
4647         };
4648         // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
4649         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4650         mine_transaction(&nodes[1], &commitment_tx[0]);
4651         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4652         let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4653         // ChannelMonitor: HTLC-Success tx
4654         assert_eq!(b_txn.len(), 1);
4655         check_spends!(b_txn[0], commitment_tx[0]);
4656         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4657         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4658         assert_eq!(b_txn[0].lock_time.0, 0); // Success tx
4659
4660         check_closed_broadcast!(nodes[1], true);
4661         check_added_monitors!(nodes[1], 1);
4662 }
4663
4664 #[test]
4665 fn test_duplicate_payment_hash_one_failure_one_success() {
4666         // Topology : A --> B --> C --> D
4667         // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
4668         // Note that because C will refuse to generate two payment secrets for the same payment hash,
4669         // we forward one of the payments onwards to D.
4670         let chanmon_cfgs = create_chanmon_cfgs(4);
4671         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4672         // When this test was written, the default base fee floated based on the HTLC count.
4673         // It is now fixed, so we simply set the fee to the expected value here.
4674         let mut config = test_default_channel_config();
4675         config.channel_config.forwarding_fee_base_msat = 196;
4676         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
4677                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4678         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4679
4680         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4681         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4682         create_announced_chan_between_nodes(&nodes, 2, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4683
4684         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4685         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4686         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4687         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4688         connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
4689
4690         let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 900_000);
4691
4692         let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200).unwrap();
4693         // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
4694         // script push size limit so that the below script length checks match
4695         // ACCEPTED_HTLC_SCRIPT_WEIGHT.
4696         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id())
4697                 .with_features(channelmanager::provided_invoice_features());
4698         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 900000, TEST_FINAL_CLTV - 40);
4699         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 900000, duplicate_payment_hash, payment_secret);
4700
4701         let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
4702         assert_eq!(commitment_txn[0].input.len(), 1);
4703         check_spends!(commitment_txn[0], chan_2.3);
4704
4705         mine_transaction(&nodes[1], &commitment_txn[0]);
4706         check_closed_broadcast!(nodes[1], true);
4707         check_added_monitors!(nodes[1], 1);
4708         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4709         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
4710
4711         let htlc_timeout_tx;
4712         { // Extract one of the two HTLC-Timeout transaction
4713                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4714                 // ChannelMonitor: timeout tx * 2-or-3
4715                 assert!(node_txn.len() == 2 || node_txn.len() == 3);
4716
4717                 check_spends!(node_txn[0], commitment_txn[0]);
4718                 assert_eq!(node_txn[0].input.len(), 1);
4719
4720                 if node_txn.len() > 2 {
4721                         check_spends!(node_txn[1], commitment_txn[0]);
4722                         assert_eq!(node_txn[1].input.len(), 1);
4723                         assert_eq!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
4724
4725                         check_spends!(node_txn[2], commitment_txn[0]);
4726                         assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
4727                 } else {
4728                         check_spends!(node_txn[1], commitment_txn[0]);
4729                         assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
4730                 }
4731
4732                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4733                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4734                 if node_txn.len() > 2 {
4735                         assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4736                 }
4737                 htlc_timeout_tx = node_txn[0].clone();
4738         }
4739
4740         nodes[2].node.claim_funds(our_payment_preimage);
4741         expect_payment_claimed!(nodes[2], duplicate_payment_hash, 900_000);
4742
4743         mine_transaction(&nodes[2], &commitment_txn[0]);
4744         check_added_monitors!(nodes[2], 2);
4745         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
4746         let events = nodes[2].node.get_and_clear_pending_msg_events();
4747         match events[0] {
4748                 MessageSendEvent::UpdateHTLCs { .. } => {},
4749                 _ => panic!("Unexpected event"),
4750         }
4751         match events[1] {
4752                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4753                 _ => panic!("Unexepected event"),
4754         }
4755         let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4756         assert_eq!(htlc_success_txn.len(), 2); // ChannelMonitor: HTLC-Success txn (*2 due to 2-HTLC outputs)
4757         check_spends!(htlc_success_txn[0], commitment_txn[0]);
4758         check_spends!(htlc_success_txn[1], commitment_txn[0]);
4759         assert_eq!(htlc_success_txn[0].input.len(), 1);
4760         assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4761         assert_eq!(htlc_success_txn[1].input.len(), 1);
4762         assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4763         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
4764         assert_ne!(htlc_success_txn[1].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
4765
4766         mine_transaction(&nodes[1], &htlc_timeout_tx);
4767         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4768         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 }]);
4769         let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4770         assert!(htlc_updates.update_add_htlcs.is_empty());
4771         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
4772         let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
4773         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
4774         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
4775         check_added_monitors!(nodes[1], 1);
4776
4777         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
4778         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4779         {
4780                 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
4781         }
4782         expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
4783
4784         // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
4785         // Note that the fee paid is effectively double as the HTLC value (including the nodes[1] fee
4786         // and nodes[2] fee) is rounded down and then claimed in full.
4787         mine_transaction(&nodes[1], &htlc_success_txn[1]);
4788         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196*2), true, true);
4789         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4790         assert!(updates.update_add_htlcs.is_empty());
4791         assert!(updates.update_fail_htlcs.is_empty());
4792         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4793         assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
4794         assert!(updates.update_fail_malformed_htlcs.is_empty());
4795         check_added_monitors!(nodes[1], 1);
4796
4797         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
4798         commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
4799
4800         let events = nodes[0].node.get_and_clear_pending_events();
4801         match events[0] {
4802                 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4803                         assert_eq!(*payment_preimage, our_payment_preimage);
4804                         assert_eq!(*payment_hash, duplicate_payment_hash);
4805                 }
4806                 _ => panic!("Unexpected event"),
4807         }
4808 }
4809
4810 #[test]
4811 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
4812         let chanmon_cfgs = create_chanmon_cfgs(2);
4813         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4814         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4815         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4816
4817         // Create some initial channels
4818         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4819
4820         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
4821         let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4822         assert_eq!(local_txn.len(), 1);
4823         assert_eq!(local_txn[0].input.len(), 1);
4824         check_spends!(local_txn[0], chan_1.3);
4825
4826         // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
4827         nodes[1].node.claim_funds(payment_preimage);
4828         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
4829         check_added_monitors!(nodes[1], 1);
4830
4831         mine_transaction(&nodes[1], &local_txn[0]);
4832         check_added_monitors!(nodes[1], 1);
4833         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4834         let events = nodes[1].node.get_and_clear_pending_msg_events();
4835         match events[0] {
4836                 MessageSendEvent::UpdateHTLCs { .. } => {},
4837                 _ => panic!("Unexpected event"),
4838         }
4839         match events[1] {
4840                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4841                 _ => panic!("Unexepected event"),
4842         }
4843         let node_tx = {
4844                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4845                 assert_eq!(node_txn.len(), 1);
4846                 assert_eq!(node_txn[0].input.len(), 1);
4847                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4848                 check_spends!(node_txn[0], local_txn[0]);
4849                 node_txn[0].clone()
4850         };
4851
4852         mine_transaction(&nodes[1], &node_tx);
4853         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4854
4855         // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
4856         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4857         assert_eq!(spend_txn.len(), 1);
4858         assert_eq!(spend_txn[0].input.len(), 1);
4859         check_spends!(spend_txn[0], node_tx);
4860         assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4861 }
4862
4863 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
4864         // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
4865         // unrevoked commitment transaction.
4866         // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
4867         // a remote RAA before they could be failed backwards (and combinations thereof).
4868         // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
4869         // use the same payment hashes.
4870         // Thus, we use a six-node network:
4871         //
4872         // A \         / E
4873         //    - C - D -
4874         // B /         \ F
4875         // And test where C fails back to A/B when D announces its latest commitment transaction
4876         let chanmon_cfgs = create_chanmon_cfgs(6);
4877         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
4878         // When this test was written, the default base fee floated based on the HTLC count.
4879         // It is now fixed, so we simply set the fee to the expected value here.
4880         let mut config = test_default_channel_config();
4881         config.channel_config.forwarding_fee_base_msat = 196;
4882         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
4883                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4884         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
4885
4886         let _chan_0_2 = create_announced_chan_between_nodes(&nodes, 0, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4887         let _chan_1_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4888         let chan_2_3 = create_announced_chan_between_nodes(&nodes, 2, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4889         let chan_3_4 = create_announced_chan_between_nodes(&nodes, 3, 4, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4890         let chan_3_5  = create_announced_chan_between_nodes(&nodes, 3, 5, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4891
4892         // Rebalance and check output sanity...
4893         send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
4894         send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
4895         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 2);
4896
4897         let ds_dust_limit = nodes[3].node.per_peer_state.read().unwrap().get(&nodes[2].node.get_our_node_id())
4898                 .unwrap().lock().unwrap().channel_by_id.get(&chan_2_3.2).unwrap().holder_dust_limit_satoshis;
4899         // 0th HTLC:
4900         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
4901         // 1st HTLC:
4902         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
4903         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
4904         // 2nd HTLC:
4905         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).unwrap()); // not added < dust limit + HTLC tx fee
4906         // 3rd HTLC:
4907         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).unwrap()); // not added < dust limit + HTLC tx fee
4908         // 4th HTLC:
4909         let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4910         // 5th HTLC:
4911         let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4912         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
4913         // 6th HTLC:
4914         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).unwrap());
4915         // 7th HTLC:
4916         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).unwrap());
4917
4918         // 8th HTLC:
4919         let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4920         // 9th HTLC:
4921         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
4922         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).unwrap()); // not added < dust limit + HTLC tx fee
4923
4924         // 10th HTLC:
4925         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
4926         // 11th HTLC:
4927         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
4928         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).unwrap());
4929
4930         // Double-check that six of the new HTLC were added
4931         // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
4932         // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
4933         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2).len(), 1);
4934         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 8);
4935
4936         // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
4937         // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
4938         nodes[4].node.fail_htlc_backwards(&payment_hash_1);
4939         nodes[4].node.fail_htlc_backwards(&payment_hash_3);
4940         nodes[4].node.fail_htlc_backwards(&payment_hash_5);
4941         nodes[4].node.fail_htlc_backwards(&payment_hash_6);
4942         check_added_monitors!(nodes[4], 0);
4943
4944         let failed_destinations = vec![
4945                 HTLCDestination::FailedPayment { payment_hash: payment_hash_1 },
4946                 HTLCDestination::FailedPayment { payment_hash: payment_hash_3 },
4947                 HTLCDestination::FailedPayment { payment_hash: payment_hash_5 },
4948                 HTLCDestination::FailedPayment { payment_hash: payment_hash_6 },
4949         ];
4950         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[4], failed_destinations);
4951         check_added_monitors!(nodes[4], 1);
4952
4953         let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
4954         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
4955         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
4956         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
4957         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
4958         commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
4959
4960         // Fail 3rd below-dust and 7th above-dust HTLCs
4961         nodes[5].node.fail_htlc_backwards(&payment_hash_2);
4962         nodes[5].node.fail_htlc_backwards(&payment_hash_4);
4963         check_added_monitors!(nodes[5], 0);
4964
4965         let failed_destinations_2 = vec![
4966                 HTLCDestination::FailedPayment { payment_hash: payment_hash_2 },
4967                 HTLCDestination::FailedPayment { payment_hash: payment_hash_4 },
4968         ];
4969         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[5], failed_destinations_2);
4970         check_added_monitors!(nodes[5], 1);
4971
4972         let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
4973         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
4974         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
4975         commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
4976
4977         let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
4978
4979         // After 4 and 2 removes respectively above in nodes[4] and nodes[5], nodes[3] should receive 6 PaymentForwardedFailed events
4980         let failed_destinations_3 = vec![
4981                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
4982                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
4983                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
4984                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
4985                 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
4986                 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
4987         ];
4988         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations_3);
4989         check_added_monitors!(nodes[3], 1);
4990         let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
4991         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
4992         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
4993         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
4994         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
4995         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
4996         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
4997         if deliver_last_raa {
4998                 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
4999         } else {
5000                 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5001         }
5002
5003         // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5004         // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5005         // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5006         // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5007         //
5008         // We now broadcast the latest commitment transaction, which *should* result in failures for
5009         // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5010         // the non-broadcast above-dust HTLCs.
5011         //
5012         // Alternatively, we may broadcast the previous commitment transaction, which should only
5013         // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5014         let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5015
5016         if announce_latest {
5017                 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5018         } else {
5019                 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5020         }
5021         let events = nodes[2].node.get_and_clear_pending_events();
5022         let close_event = if deliver_last_raa {
5023                 assert_eq!(events.len(), 2 + 6);
5024                 events.last().clone().unwrap()
5025         } else {
5026                 assert_eq!(events.len(), 1);
5027                 events.last().clone().unwrap()
5028         };
5029         match close_event {
5030                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5031                 _ => panic!("Unexpected event"),
5032         }
5033
5034         connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5035         check_closed_broadcast!(nodes[2], true);
5036         if deliver_last_raa {
5037                 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5038
5039                 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();
5040                 expect_htlc_handling_failed_destinations!(nodes[2].node.get_and_clear_pending_events(), expected_destinations);
5041         } else {
5042                 let expected_destinations: Vec<HTLCDestination> = if announce_latest {
5043                         repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(9).collect()
5044                 } else {
5045                         repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(6).collect()
5046                 };
5047
5048                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], expected_destinations);
5049         }
5050         check_added_monitors!(nodes[2], 3);
5051
5052         let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5053         assert_eq!(cs_msgs.len(), 2);
5054         let mut a_done = false;
5055         for msg in cs_msgs {
5056                 match msg {
5057                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5058                                 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5059                                 // should be failed-backwards here.
5060                                 let target = if *node_id == nodes[0].node.get_our_node_id() {
5061                                         // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5062                                         for htlc in &updates.update_fail_htlcs {
5063                                                 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 });
5064                                         }
5065                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5066                                         assert!(!a_done);
5067                                         a_done = true;
5068                                         &nodes[0]
5069                                 } else {
5070                                         // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5071                                         for htlc in &updates.update_fail_htlcs {
5072                                                 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5073                                         }
5074                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5075                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5076                                         &nodes[1]
5077                                 };
5078                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5079                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5080                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5081                                 if announce_latest {
5082                                         target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5083                                         if *node_id == nodes[0].node.get_our_node_id() {
5084                                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5085                                         }
5086                                 }
5087                                 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5088                         },
5089                         _ => panic!("Unexpected event"),
5090                 }
5091         }
5092
5093         let as_events = nodes[0].node.get_and_clear_pending_events();
5094         assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5095         let mut as_failds = HashSet::new();
5096         let mut as_updates = 0;
5097         for event in as_events.iter() {
5098                 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref network_update, .. } = event {
5099                         assert!(as_failds.insert(*payment_hash));
5100                         if *payment_hash != payment_hash_2 {
5101                                 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5102                         } else {
5103                                 assert!(!payment_failed_permanently);
5104                         }
5105                         if network_update.is_some() {
5106                                 as_updates += 1;
5107                         }
5108                 } else { panic!("Unexpected event"); }
5109         }
5110         assert!(as_failds.contains(&payment_hash_1));
5111         assert!(as_failds.contains(&payment_hash_2));
5112         if announce_latest {
5113                 assert!(as_failds.contains(&payment_hash_3));
5114                 assert!(as_failds.contains(&payment_hash_5));
5115         }
5116         assert!(as_failds.contains(&payment_hash_6));
5117
5118         let bs_events = nodes[1].node.get_and_clear_pending_events();
5119         assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5120         let mut bs_failds = HashSet::new();
5121         let mut bs_updates = 0;
5122         for event in bs_events.iter() {
5123                 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref network_update, .. } = event {
5124                         assert!(bs_failds.insert(*payment_hash));
5125                         if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5126                                 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5127                         } else {
5128                                 assert!(!payment_failed_permanently);
5129                         }
5130                         if network_update.is_some() {
5131                                 bs_updates += 1;
5132                         }
5133                 } else { panic!("Unexpected event"); }
5134         }
5135         assert!(bs_failds.contains(&payment_hash_1));
5136         assert!(bs_failds.contains(&payment_hash_2));
5137         if announce_latest {
5138                 assert!(bs_failds.contains(&payment_hash_4));
5139         }
5140         assert!(bs_failds.contains(&payment_hash_5));
5141
5142         // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5143         // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5144         // unknown-preimage-etc, B should have gotten 2. Thus, in the
5145         // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5146         assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5147         assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5148 }
5149
5150 #[test]
5151 fn test_fail_backwards_latest_remote_announce_a() {
5152         do_test_fail_backwards_unrevoked_remote_announce(false, true);
5153 }
5154
5155 #[test]
5156 fn test_fail_backwards_latest_remote_announce_b() {
5157         do_test_fail_backwards_unrevoked_remote_announce(true, true);
5158 }
5159
5160 #[test]
5161 fn test_fail_backwards_previous_remote_announce() {
5162         do_test_fail_backwards_unrevoked_remote_announce(false, false);
5163         // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5164         // tested for in test_commitment_revoked_fail_backward_exhaustive()
5165 }
5166
5167 #[test]
5168 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5169         let chanmon_cfgs = create_chanmon_cfgs(2);
5170         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5171         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5172         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5173
5174         // Create some initial channels
5175         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5176
5177         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5178         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5179         assert_eq!(local_txn[0].input.len(), 1);
5180         check_spends!(local_txn[0], chan_1.3);
5181
5182         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5183         mine_transaction(&nodes[0], &local_txn[0]);
5184         check_closed_broadcast!(nodes[0], true);
5185         check_added_monitors!(nodes[0], 1);
5186         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5187         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5188
5189         let htlc_timeout = {
5190                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5191                 assert_eq!(node_txn.len(), 1);
5192                 assert_eq!(node_txn[0].input.len(), 1);
5193                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5194                 check_spends!(node_txn[0], local_txn[0]);
5195                 node_txn[0].clone()
5196         };
5197
5198         mine_transaction(&nodes[0], &htlc_timeout);
5199         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5200         expect_payment_failed!(nodes[0], our_payment_hash, false);
5201
5202         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5203         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5204         assert_eq!(spend_txn.len(), 3);
5205         check_spends!(spend_txn[0], local_txn[0]);
5206         assert_eq!(spend_txn[1].input.len(), 1);
5207         check_spends!(spend_txn[1], htlc_timeout);
5208         assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5209         assert_eq!(spend_txn[2].input.len(), 2);
5210         check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5211         assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5212                 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5213 }
5214
5215 #[test]
5216 fn test_key_derivation_params() {
5217         // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with a key
5218         // manager rotation to test that `channel_keys_id` returned in
5219         // [`SpendableOutputDescriptor::DelayedPaymentOutput`] let us re-derive the channel key set to
5220         // then derive a `delayed_payment_key`.
5221
5222         let chanmon_cfgs = create_chanmon_cfgs(3);
5223
5224         // We manually create the node configuration to backup the seed.
5225         let seed = [42; 32];
5226         let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5227         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);
5228         let network_graph = Arc::new(NetworkGraph::new(chanmon_cfgs[0].chain_source.genesis_hash, &chanmon_cfgs[0].logger));
5229         let router = test_utils::TestRouter::new(network_graph.clone());
5230         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, features: channelmanager::provided_init_features() };
5231         let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5232         node_cfgs.remove(0);
5233         node_cfgs.insert(0, node);
5234
5235         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5236         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5237
5238         // Create some initial channels
5239         // Create a dummy channel to advance index by one and thus test re-derivation correctness
5240         // for node 0
5241         let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5242         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5243         assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5244
5245         // Ensure all nodes are at the same height
5246         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5247         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5248         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5249         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5250
5251         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5252         let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5253         let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5254         assert_eq!(local_txn_1[0].input.len(), 1);
5255         check_spends!(local_txn_1[0], chan_1.3);
5256
5257         // We check funding pubkey are unique
5258         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]));
5259         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]));
5260         if from_0_funding_key_0 == from_1_funding_key_0
5261             || from_0_funding_key_0 == from_1_funding_key_1
5262             || from_0_funding_key_1 == from_1_funding_key_0
5263             || from_0_funding_key_1 == from_1_funding_key_1 {
5264                 panic!("Funding pubkeys aren't unique");
5265         }
5266
5267         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5268         mine_transaction(&nodes[0], &local_txn_1[0]);
5269         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5270         check_closed_broadcast!(nodes[0], true);
5271         check_added_monitors!(nodes[0], 1);
5272         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5273
5274         let htlc_timeout = {
5275                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5276                 assert_eq!(node_txn.len(), 1);
5277                 assert_eq!(node_txn[0].input.len(), 1);
5278                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5279                 check_spends!(node_txn[0], local_txn_1[0]);
5280                 node_txn[0].clone()
5281         };
5282
5283         mine_transaction(&nodes[0], &htlc_timeout);
5284         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5285         expect_payment_failed!(nodes[0], our_payment_hash, false);
5286
5287         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5288         let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5289         let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5290         assert_eq!(spend_txn.len(), 3);
5291         check_spends!(spend_txn[0], local_txn_1[0]);
5292         assert_eq!(spend_txn[1].input.len(), 1);
5293         check_spends!(spend_txn[1], htlc_timeout);
5294         assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5295         assert_eq!(spend_txn[2].input.len(), 2);
5296         check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5297         assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5298                 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5299 }
5300
5301 #[test]
5302 fn test_static_output_closing_tx() {
5303         let chanmon_cfgs = create_chanmon_cfgs(2);
5304         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5305         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5306         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5307
5308         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5309
5310         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5311         let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5312
5313         mine_transaction(&nodes[0], &closing_tx);
5314         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5315         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5316
5317         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5318         assert_eq!(spend_txn.len(), 1);
5319         check_spends!(spend_txn[0], closing_tx);
5320
5321         mine_transaction(&nodes[1], &closing_tx);
5322         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5323         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5324
5325         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5326         assert_eq!(spend_txn.len(), 1);
5327         check_spends!(spend_txn[0], closing_tx);
5328 }
5329
5330 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5331         let chanmon_cfgs = create_chanmon_cfgs(2);
5332         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5333         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5334         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5335         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5336
5337         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3_000_000 });
5338
5339         // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5340         // present in B's local commitment transaction, but none of A's commitment transactions.
5341         nodes[1].node.claim_funds(payment_preimage);
5342         check_added_monitors!(nodes[1], 1);
5343         expect_payment_claimed!(nodes[1], payment_hash, if use_dust { 50000 } else { 3_000_000 });
5344
5345         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5346         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5347         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
5348
5349         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5350         check_added_monitors!(nodes[0], 1);
5351         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5352         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5353         check_added_monitors!(nodes[1], 1);
5354
5355         let starting_block = nodes[1].best_block_info();
5356         let mut block = Block {
5357                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
5358                 txdata: vec![],
5359         };
5360         for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5361                 connect_block(&nodes[1], &block);
5362                 block.header.prev_blockhash = block.block_hash();
5363         }
5364         test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5365         check_closed_broadcast!(nodes[1], true);
5366         check_added_monitors!(nodes[1], 1);
5367         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5368 }
5369
5370 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5371         let chanmon_cfgs = create_chanmon_cfgs(2);
5372         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5373         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5374         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5375         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5376
5377         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5378         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
5379         check_added_monitors!(nodes[0], 1);
5380
5381         let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5382
5383         // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5384         // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5385         // to "time out" the HTLC.
5386
5387         let starting_block = nodes[1].best_block_info();
5388         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
5389
5390         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5391                 connect_block(&nodes[0], &Block { header, txdata: Vec::new()});
5392                 header.prev_blockhash = header.block_hash();
5393         }
5394         test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5395         check_closed_broadcast!(nodes[0], true);
5396         check_added_monitors!(nodes[0], 1);
5397         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5398 }
5399
5400 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5401         let chanmon_cfgs = create_chanmon_cfgs(3);
5402         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5403         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5404         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5405         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5406
5407         // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5408         // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5409         // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5410         // actually revoked.
5411         let htlc_value = if use_dust { 50000 } else { 3000000 };
5412         let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5413         nodes[1].node.fail_htlc_backwards(&our_payment_hash);
5414         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
5415         check_added_monitors!(nodes[1], 1);
5416
5417         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5418         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5419         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5420         check_added_monitors!(nodes[0], 1);
5421         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5422         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5423         check_added_monitors!(nodes[1], 1);
5424         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5425         check_added_monitors!(nodes[1], 1);
5426         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5427
5428         if check_revoke_no_close {
5429                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5430                 check_added_monitors!(nodes[0], 1);
5431         }
5432
5433         let starting_block = nodes[1].best_block_info();
5434         let mut block = Block {
5435                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
5436                 txdata: vec![],
5437         };
5438         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5439                 connect_block(&nodes[0], &block);
5440                 block.header.prev_blockhash = block.block_hash();
5441         }
5442         if !check_revoke_no_close {
5443                 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5444                 check_closed_broadcast!(nodes[0], true);
5445                 check_added_monitors!(nodes[0], 1);
5446                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5447         } else {
5448                 expect_payment_failed!(nodes[0], our_payment_hash, true);
5449         }
5450 }
5451
5452 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5453 // There are only a few cases to test here:
5454 //  * its not really normative behavior, but we test that below-dust HTLCs "included" in
5455 //    broadcastable commitment transactions result in channel closure,
5456 //  * its included in an unrevoked-but-previous remote commitment transaction,
5457 //  * its included in the latest remote or local commitment transactions.
5458 // We test each of the three possible commitment transactions individually and use both dust and
5459 // non-dust HTLCs.
5460 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5461 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5462 // tested for at least one of the cases in other tests.
5463 #[test]
5464 fn htlc_claim_single_commitment_only_a() {
5465         do_htlc_claim_local_commitment_only(true);
5466         do_htlc_claim_local_commitment_only(false);
5467
5468         do_htlc_claim_current_remote_commitment_only(true);
5469         do_htlc_claim_current_remote_commitment_only(false);
5470 }
5471
5472 #[test]
5473 fn htlc_claim_single_commitment_only_b() {
5474         do_htlc_claim_previous_remote_commitment_only(true, false);
5475         do_htlc_claim_previous_remote_commitment_only(false, false);
5476         do_htlc_claim_previous_remote_commitment_only(true, true);
5477         do_htlc_claim_previous_remote_commitment_only(false, true);
5478 }
5479
5480 #[test]
5481 #[should_panic]
5482 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5483         let chanmon_cfgs = create_chanmon_cfgs(2);
5484         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5485         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5486         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5487         // Force duplicate randomness for every get-random call
5488         for node in nodes.iter() {
5489                 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
5490         }
5491
5492         // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5493         let channel_value_satoshis=10000;
5494         let push_msat=10001;
5495         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5496         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5497         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &node0_to_1_send_open_channel);
5498         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
5499
5500         // Create a second channel with the same random values. This used to panic due to a colliding
5501         // channel_id, but now panics due to a colliding outbound SCID alias.
5502         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5503 }
5504
5505 #[test]
5506 fn bolt2_open_channel_sending_node_checks_part2() {
5507         let chanmon_cfgs = create_chanmon_cfgs(2);
5508         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5509         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5510         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5511
5512         // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5513         let channel_value_satoshis=2^24;
5514         let push_msat=10001;
5515         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5516
5517         // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5518         let channel_value_satoshis=10000;
5519         // Test when push_msat is equal to 1000 * funding_satoshis.
5520         let push_msat=1000*channel_value_satoshis+1;
5521         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5522
5523         // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5524         let channel_value_satoshis=10000;
5525         let push_msat=10001;
5526         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
5527         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5528         assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5529
5530         // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5531         // 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
5532         assert!(node0_to_1_send_open_channel.channel_flags<=1);
5533
5534         // 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.
5535         assert!(BREAKDOWN_TIMEOUT>0);
5536         assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5537
5538         // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5539         let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5540         assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5541
5542         // 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.
5543         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5544         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5545         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5546         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5547         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5548 }
5549
5550 #[test]
5551 fn bolt2_open_channel_sane_dust_limit() {
5552         let chanmon_cfgs = create_chanmon_cfgs(2);
5553         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5554         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5555         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5556
5557         let channel_value_satoshis=1000000;
5558         let push_msat=10001;
5559         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5560         let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5561         node0_to_1_send_open_channel.dust_limit_satoshis = 547;
5562         node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
5563
5564         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &node0_to_1_send_open_channel);
5565         let events = nodes[1].node.get_and_clear_pending_msg_events();
5566         let err_msg = match events[0] {
5567                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
5568                         msg.clone()
5569                 },
5570                 _ => panic!("Unexpected event"),
5571         };
5572         assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
5573 }
5574
5575 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5576 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5577 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5578 // is no longer affordable once it's freed.
5579 #[test]
5580 fn test_fail_holding_cell_htlc_upon_free() {
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_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5586
5587         // First nodes[0] generates an update_fee, setting the channel's
5588         // pending_update_fee.
5589         {
5590                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5591                 *feerate_lock += 20;
5592         }
5593         nodes[0].node.timer_tick_occurred();
5594         check_added_monitors!(nodes[0], 1);
5595
5596         let events = nodes[0].node.get_and_clear_pending_msg_events();
5597         assert_eq!(events.len(), 1);
5598         let (update_msg, commitment_signed) = match events[0] {
5599                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5600                         (update_fee.as_ref(), commitment_signed)
5601                 },
5602                 _ => panic!("Unexpected event"),
5603         };
5604
5605         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5606
5607         let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5608         let channel_reserve = chan_stat.channel_reserve_msat;
5609         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5610         let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
5611
5612         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5613         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
5614         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
5615
5616         // Send a payment which passes reserve checks but gets stuck in the holding cell.
5617         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5618         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5619         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5620
5621         // Flush the pending fee update.
5622         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5623         let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5624         check_added_monitors!(nodes[1], 1);
5625         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
5626         check_added_monitors!(nodes[0], 1);
5627
5628         // Upon receipt of the RAA, there will be an attempt to resend the holding cell
5629         // HTLC, but now that the fee has been raised the payment will now fail, causing
5630         // us to surface its failure to the user.
5631         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5632         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5633         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Freeing holding cell with 1 HTLC updates in channel {}", hex::encode(chan.2)), 1);
5634         let failure_log = format!("Failed to send HTLC with payment_hash {} due to Cannot send value that would put our balance under counterparty-announced channel reserve value ({}) in channel {}",
5635                 hex::encode(our_payment_hash.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
5636         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
5637
5638         // Check that the payment failed to be sent out.
5639         let events = nodes[0].node.get_and_clear_pending_events();
5640         assert_eq!(events.len(), 1);
5641         match &events[0] {
5642                 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, ref network_update, ref all_paths_failed, ref short_channel_id, .. } => {
5643                         assert_eq!(PaymentId(our_payment_hash.0), *payment_id.as_ref().unwrap());
5644                         assert_eq!(our_payment_hash.clone(), *payment_hash);
5645                         assert_eq!(*payment_failed_permanently, false);
5646                         assert_eq!(*all_paths_failed, true);
5647                         assert_eq!(*network_update, None);
5648                         assert_eq!(*short_channel_id, Some(route.paths[0][0].short_channel_id));
5649                 },
5650                 _ => panic!("Unexpected event"),
5651         }
5652 }
5653
5654 // Test that if multiple HTLCs are released from the holding cell and one is
5655 // valid but the other is no longer valid upon release, the valid HTLC can be
5656 // successfully completed while the other one fails as expected.
5657 #[test]
5658 fn test_free_and_fail_holding_cell_htlcs() {
5659         let chanmon_cfgs = create_chanmon_cfgs(2);
5660         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5661         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5662         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5663         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5664
5665         // First nodes[0] generates an update_fee, setting the channel's
5666         // pending_update_fee.
5667         {
5668                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5669                 *feerate_lock += 200;
5670         }
5671         nodes[0].node.timer_tick_occurred();
5672         check_added_monitors!(nodes[0], 1);
5673
5674         let events = nodes[0].node.get_and_clear_pending_msg_events();
5675         assert_eq!(events.len(), 1);
5676         let (update_msg, commitment_signed) = match events[0] {
5677                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5678                         (update_fee.as_ref(), commitment_signed)
5679                 },
5680                 _ => panic!("Unexpected event"),
5681         };
5682
5683         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5684
5685         let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5686         let channel_reserve = chan_stat.channel_reserve_msat;
5687         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5688         let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
5689
5690         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5691         let amt_1 = 20000;
5692         let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors) - amt_1;
5693         let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
5694         let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
5695
5696         // Send 2 payments which pass reserve checks but get stuck in the holding cell.
5697         nodes[0].node.send_payment(&route_1, payment_hash_1, &Some(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
5698         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5699         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
5700         let payment_id_2 = PaymentId(nodes[0].keys_manager.get_secure_random_bytes());
5701         nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2), payment_id_2).unwrap();
5702         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5703         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
5704
5705         // Flush the pending fee update.
5706         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5707         let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5708         check_added_monitors!(nodes[1], 1);
5709         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
5710         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
5711         check_added_monitors!(nodes[0], 2);
5712
5713         // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
5714         // but now that the fee has been raised the second payment will now fail, causing us
5715         // to surface its failure to the user. The first payment should succeed.
5716         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5717         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5718         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Freeing holding cell with 2 HTLC updates in channel {}", hex::encode(chan.2)), 1);
5719         let failure_log = format!("Failed to send HTLC with payment_hash {} due to Cannot send value that would put our balance under counterparty-announced channel reserve value ({}) in channel {}",
5720                 hex::encode(payment_hash_2.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
5721         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
5722
5723         // Check that the second payment failed to be sent out.
5724         let events = nodes[0].node.get_and_clear_pending_events();
5725         assert_eq!(events.len(), 1);
5726         match &events[0] {
5727                 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, ref network_update, ref all_paths_failed, ref short_channel_id, .. } => {
5728                         assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
5729                         assert_eq!(payment_hash_2.clone(), *payment_hash);
5730                         assert_eq!(*payment_failed_permanently, false);
5731                         assert_eq!(*all_paths_failed, true);
5732                         assert_eq!(*network_update, None);
5733                         assert_eq!(*short_channel_id, Some(route_2.paths[0][0].short_channel_id));
5734                 },
5735                 _ => panic!("Unexpected event"),
5736         }
5737
5738         // Complete the first payment and the RAA from the fee update.
5739         let (payment_event, send_raa_event) = {
5740                 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
5741                 assert_eq!(msgs.len(), 2);
5742                 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
5743         };
5744         let raa = match send_raa_event {
5745                 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
5746                 _ => panic!("Unexpected event"),
5747         };
5748         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
5749         check_added_monitors!(nodes[1], 1);
5750         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5751         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5752         let events = nodes[1].node.get_and_clear_pending_events();
5753         assert_eq!(events.len(), 1);
5754         match events[0] {
5755                 Event::PendingHTLCsForwardable { .. } => {},
5756                 _ => panic!("Unexpected event"),
5757         }
5758         nodes[1].node.process_pending_htlc_forwards();
5759         let events = nodes[1].node.get_and_clear_pending_events();
5760         assert_eq!(events.len(), 1);
5761         match events[0] {
5762                 Event::PaymentClaimable { .. } => {},
5763                 _ => panic!("Unexpected event"),
5764         }
5765         nodes[1].node.claim_funds(payment_preimage_1);
5766         check_added_monitors!(nodes[1], 1);
5767         expect_payment_claimed!(nodes[1], payment_hash_1, amt_1);
5768
5769         let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5770         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
5771         commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
5772         expect_payment_sent!(nodes[0], payment_preimage_1);
5773 }
5774
5775 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
5776 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
5777 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
5778 // once it's freed.
5779 #[test]
5780 fn test_fail_holding_cell_htlc_upon_free_multihop() {
5781         let chanmon_cfgs = create_chanmon_cfgs(3);
5782         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5783         // When this test was written, the default base fee floated based on the HTLC count.
5784         // It is now fixed, so we simply set the fee to the expected value here.
5785         let mut config = test_default_channel_config();
5786         config.channel_config.forwarding_fee_base_msat = 196;
5787         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5788         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5789         let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5790         let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5791
5792         // First nodes[1] generates an update_fee, setting the channel's
5793         // pending_update_fee.
5794         {
5795                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
5796                 *feerate_lock += 20;
5797         }
5798         nodes[1].node.timer_tick_occurred();
5799         check_added_monitors!(nodes[1], 1);
5800
5801         let events = nodes[1].node.get_and_clear_pending_msg_events();
5802         assert_eq!(events.len(), 1);
5803         let (update_msg, commitment_signed) = match events[0] {
5804                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5805                         (update_fee.as_ref(), commitment_signed)
5806                 },
5807                 _ => panic!("Unexpected event"),
5808         };
5809
5810         nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
5811
5812         let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan_0_1.2);
5813         let channel_reserve = chan_stat.channel_reserve_msat;
5814         let feerate = get_feerate!(nodes[0], nodes[1], chan_0_1.2);
5815         let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan_0_1.2);
5816
5817         // Send a payment which passes reserve checks but gets stuck in the holding cell.
5818         let feemsat = 239;
5819         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
5820         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors) - total_routing_fee_msat;
5821         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
5822         let payment_event = {
5823                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5824                 check_added_monitors!(nodes[0], 1);
5825
5826                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
5827                 assert_eq!(events.len(), 1);
5828
5829                 SendEvent::from_event(events.remove(0))
5830         };
5831         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5832         check_added_monitors!(nodes[1], 0);
5833         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5834         expect_pending_htlcs_forwardable!(nodes[1]);
5835
5836         chan_stat = get_channel_value_stat!(nodes[1], nodes[2], chan_1_2.2);
5837         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5838
5839         // Flush the pending fee update.
5840         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
5841         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5842         check_added_monitors!(nodes[2], 1);
5843         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
5844         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
5845         check_added_monitors!(nodes[1], 2);
5846
5847         // A final RAA message is generated to finalize the fee update.
5848         let events = nodes[1].node.get_and_clear_pending_msg_events();
5849         assert_eq!(events.len(), 1);
5850
5851         let raa_msg = match &events[0] {
5852                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
5853                         msg.clone()
5854                 },
5855                 _ => panic!("Unexpected event"),
5856         };
5857
5858         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
5859         check_added_monitors!(nodes[2], 1);
5860         assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
5861
5862         // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
5863         let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
5864         assert_eq!(process_htlc_forwards_event.len(), 2);
5865         match &process_htlc_forwards_event[0] {
5866                 &Event::PendingHTLCsForwardable { .. } => {},
5867                 _ => panic!("Unexpected event"),
5868         }
5869
5870         // In response, we call ChannelManager's process_pending_htlc_forwards
5871         nodes[1].node.process_pending_htlc_forwards();
5872         check_added_monitors!(nodes[1], 1);
5873
5874         // This causes the HTLC to be failed backwards.
5875         let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
5876         assert_eq!(fail_event.len(), 1);
5877         let (fail_msg, commitment_signed) = match &fail_event[0] {
5878                 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
5879                         assert_eq!(updates.update_add_htlcs.len(), 0);
5880                         assert_eq!(updates.update_fulfill_htlcs.len(), 0);
5881                         assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
5882                         assert_eq!(updates.update_fail_htlcs.len(), 1);
5883                         (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
5884                 },
5885                 _ => panic!("Unexpected event"),
5886         };
5887
5888         // Pass the failure messages back to nodes[0].
5889         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
5890         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
5891
5892         // Complete the HTLC failure+removal process.
5893         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5894         check_added_monitors!(nodes[0], 1);
5895         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
5896         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
5897         check_added_monitors!(nodes[1], 2);
5898         let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
5899         assert_eq!(final_raa_event.len(), 1);
5900         let raa = match &final_raa_event[0] {
5901                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
5902                 _ => panic!("Unexpected event"),
5903         };
5904         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
5905         expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
5906         check_added_monitors!(nodes[0], 1);
5907 }
5908
5909 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
5910 // 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.
5911 //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.
5912
5913 #[test]
5914 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
5915         //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
5916         let chanmon_cfgs = create_chanmon_cfgs(2);
5917         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5918         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5919         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5920         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5921
5922         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
5923         route.paths[0][0].fee_msat = 100;
5924
5925         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)), true, APIError::ChannelUnavailable { ref err },
5926                 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
5927         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5928         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
5929 }
5930
5931 #[test]
5932 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
5933         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
5934         let chanmon_cfgs = create_chanmon_cfgs(2);
5935         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5936         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5937         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5938         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5939
5940         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
5941         route.paths[0][0].fee_msat = 0;
5942         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)), true, APIError::ChannelUnavailable { ref err },
5943                 assert_eq!(err, "Cannot send 0-msat HTLC"));
5944
5945         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5946         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
5947 }
5948
5949 #[test]
5950 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
5951         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
5952         let chanmon_cfgs = create_chanmon_cfgs(2);
5953         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5954         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5955         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5956         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5957
5958         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
5959         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5960         check_added_monitors!(nodes[0], 1);
5961         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5962         updates.update_add_htlcs[0].amount_msat = 0;
5963
5964         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5965         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
5966         check_closed_broadcast!(nodes[1], true).unwrap();
5967         check_added_monitors!(nodes[1], 1);
5968         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
5969 }
5970
5971 #[test]
5972 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
5973         //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
5974         //It is enforced when constructing a route.
5975         let chanmon_cfgs = create_chanmon_cfgs(2);
5976         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5977         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5978         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5979         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5980
5981         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
5982                 .with_features(channelmanager::provided_invoice_features());
5983         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000, 0);
5984         route.paths[0].last_mut().unwrap().cltv_expiry_delta = 500000001;
5985         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)), true, APIError::InvalidRoute { ref err },
5986                 assert_eq!(err, &"Channel CLTV overflowed?"));
5987 }
5988
5989 #[test]
5990 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
5991         //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.
5992         //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
5993         //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
5994         let chanmon_cfgs = create_chanmon_cfgs(2);
5995         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5996         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5997         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5998         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5999         let max_accepted_htlcs = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6000                 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6001
6002         for i in 0..max_accepted_htlcs {
6003                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6004                 let payment_event = {
6005                         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6006                         check_added_monitors!(nodes[0], 1);
6007
6008                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6009                         assert_eq!(events.len(), 1);
6010                         if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6011                                 assert_eq!(htlcs[0].htlc_id, i);
6012                         } else {
6013                                 assert!(false);
6014                         }
6015                         SendEvent::from_event(events.remove(0))
6016                 };
6017                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6018                 check_added_monitors!(nodes[1], 0);
6019                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6020
6021                 expect_pending_htlcs_forwardable!(nodes[1]);
6022                 expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6023         }
6024         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6025         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)), true, APIError::ChannelUnavailable { ref err },
6026                 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6027
6028         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6029         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6030 }
6031
6032 #[test]
6033 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6034         //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.
6035         let chanmon_cfgs = create_chanmon_cfgs(2);
6036         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6037         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6038         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6039         let channel_value = 100000;
6040         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6041         let max_in_flight = get_channel_value_stat!(nodes[0], nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat;
6042
6043         send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6044
6045         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6046         // Manually create a route over our max in flight (which our router normally automatically
6047         // limits us to.
6048         route.paths[0][0].fee_msat =  max_in_flight + 1;
6049         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)), true, APIError::ChannelUnavailable { ref err },
6050                 assert!(regex::Regex::new(r"Cannot send value that would put us over the max HTLC value in flight our peer will accept \(\d+\)").unwrap().is_match(err)));
6051
6052         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6053         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send value that would put us over the max HTLC value in flight our peer will accept".to_string(), 1);
6054
6055         send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6056 }
6057
6058 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6059 #[test]
6060 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6061         //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6062         let chanmon_cfgs = create_chanmon_cfgs(2);
6063         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6064         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6065         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6066         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6067         let htlc_minimum_msat: u64;
6068         {
6069                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
6070                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
6071                 let channel = chan_lock.channel_by_id.get(&chan.2).unwrap();
6072                 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6073         }
6074
6075         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6076         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6077         check_added_monitors!(nodes[0], 1);
6078         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6079         updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6080         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6081         assert!(nodes[1].node.list_channels().is_empty());
6082         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6083         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()));
6084         check_added_monitors!(nodes[1], 1);
6085         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6086 }
6087
6088 #[test]
6089 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6090         //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
6091         let chanmon_cfgs = create_chanmon_cfgs(2);
6092         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6093         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6094         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6095         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6096
6097         let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6098         let channel_reserve = chan_stat.channel_reserve_msat;
6099         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
6100         let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
6101         // The 2* and +1 are for the fee spike reserve.
6102         let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6103
6104         let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6105         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6106         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6107         check_added_monitors!(nodes[0], 1);
6108         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6109
6110         // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6111         // at this time channel-initiatee receivers are not required to enforce that senders
6112         // respect the fee_spike_reserve.
6113         updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6114         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6115
6116         assert!(nodes[1].node.list_channels().is_empty());
6117         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6118         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6119         check_added_monitors!(nodes[1], 1);
6120         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6121 }
6122
6123 #[test]
6124 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6125         //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6126         //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6127         let chanmon_cfgs = create_chanmon_cfgs(2);
6128         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6129         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6130         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6131         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6132
6133         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3999999);
6134         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6135         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6136         let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6137         let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &Some(our_payment_secret), cur_height, &None).unwrap();
6138         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6139
6140         let mut msg = msgs::UpdateAddHTLC {
6141                 channel_id: chan.2,
6142                 htlc_id: 0,
6143                 amount_msat: 1000,
6144                 payment_hash: our_payment_hash,
6145                 cltv_expiry: htlc_cltv,
6146                 onion_routing_packet: onion_packet.clone(),
6147         };
6148
6149         for i in 0..super::channel::OUR_MAX_HTLCS {
6150                 msg.htlc_id = i as u64;
6151                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6152         }
6153         msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6154         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6155
6156         assert!(nodes[1].node.list_channels().is_empty());
6157         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6158         assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6159         check_added_monitors!(nodes[1], 1);
6160         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6161 }
6162
6163 #[test]
6164 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6165         //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
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, 1000000, 1000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6171
6172         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6173         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6174         check_added_monitors!(nodes[0], 1);
6175         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6176         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;
6177         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6178
6179         assert!(nodes[1].node.list_channels().is_empty());
6180         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6181         assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6182         check_added_monitors!(nodes[1], 1);
6183         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6184 }
6185
6186 #[test]
6187 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6188         //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6189         let chanmon_cfgs = create_chanmon_cfgs(2);
6190         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6191         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6192         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6193
6194         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6195         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6196         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6197         check_added_monitors!(nodes[0], 1);
6198         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6199         updates.update_add_htlcs[0].cltv_expiry = 500000000;
6200         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6201
6202         assert!(nodes[1].node.list_channels().is_empty());
6203         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6204         assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6205         check_added_monitors!(nodes[1], 1);
6206         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6207 }
6208
6209 #[test]
6210 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6211         //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6212         // We test this by first testing that that repeated HTLCs pass commitment signature checks
6213         // after disconnect and that non-sequential htlc_ids result in a channel failure.
6214         let chanmon_cfgs = create_chanmon_cfgs(2);
6215         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6216         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6217         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6218
6219         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6220         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6221         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6222         check_added_monitors!(nodes[0], 1);
6223         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6224         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6225
6226         //Disconnect and Reconnect
6227         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6228         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6229         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
6230         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6231         assert_eq!(reestablish_1.len(), 1);
6232         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
6233         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6234         assert_eq!(reestablish_2.len(), 1);
6235         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6236         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6237         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6238         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6239
6240         //Resend HTLC
6241         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6242         assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6243         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6244         check_added_monitors!(nodes[1], 1);
6245         let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6246
6247         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6248
6249         assert!(nodes[1].node.list_channels().is_empty());
6250         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6251         assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6252         check_added_monitors!(nodes[1], 1);
6253         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6254 }
6255
6256 #[test]
6257 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6258         //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.
6259
6260         let chanmon_cfgs = create_chanmon_cfgs(2);
6261         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6262         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6263         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6264         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6265         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6266         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6267
6268         check_added_monitors!(nodes[0], 1);
6269         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6270         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6271
6272         let update_msg = msgs::UpdateFulfillHTLC{
6273                 channel_id: chan.2,
6274                 htlc_id: 0,
6275                 payment_preimage: our_payment_preimage,
6276         };
6277
6278         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6279
6280         assert!(nodes[0].node.list_channels().is_empty());
6281         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6282         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()));
6283         check_added_monitors!(nodes[0], 1);
6284         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6285 }
6286
6287 #[test]
6288 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6289         //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.
6290
6291         let chanmon_cfgs = create_chanmon_cfgs(2);
6292         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6293         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6294         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6295         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6296
6297         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6298         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6299         check_added_monitors!(nodes[0], 1);
6300         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6301         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6302
6303         let update_msg = msgs::UpdateFailHTLC{
6304                 channel_id: chan.2,
6305                 htlc_id: 0,
6306                 reason: msgs::OnionErrorPacket { data: Vec::new()},
6307         };
6308
6309         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6310
6311         assert!(nodes[0].node.list_channels().is_empty());
6312         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6313         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()));
6314         check_added_monitors!(nodes[0], 1);
6315         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6316 }
6317
6318 #[test]
6319 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6320         //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.
6321
6322         let chanmon_cfgs = create_chanmon_cfgs(2);
6323         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6324         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6325         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6326         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6327
6328         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6329         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6330         check_added_monitors!(nodes[0], 1);
6331         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6332         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6333         let update_msg = msgs::UpdateFailMalformedHTLC{
6334                 channel_id: chan.2,
6335                 htlc_id: 0,
6336                 sha256_of_onion: [1; 32],
6337                 failure_code: 0x8000,
6338         };
6339
6340         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6341
6342         assert!(nodes[0].node.list_channels().is_empty());
6343         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6344         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()));
6345         check_added_monitors!(nodes[0], 1);
6346         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6347 }
6348
6349 #[test]
6350 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6351         //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6352
6353         let chanmon_cfgs = create_chanmon_cfgs(2);
6354         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6355         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6356         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6357         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6358
6359         let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6360
6361         nodes[1].node.claim_funds(our_payment_preimage);
6362         check_added_monitors!(nodes[1], 1);
6363         expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6364
6365         let events = nodes[1].node.get_and_clear_pending_msg_events();
6366         assert_eq!(events.len(), 1);
6367         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6368                 match events[0] {
6369                         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, .. } } => {
6370                                 assert!(update_add_htlcs.is_empty());
6371                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6372                                 assert!(update_fail_htlcs.is_empty());
6373                                 assert!(update_fail_malformed_htlcs.is_empty());
6374                                 assert!(update_fee.is_none());
6375                                 update_fulfill_htlcs[0].clone()
6376                         },
6377                         _ => panic!("Unexpected event"),
6378                 }
6379         };
6380
6381         update_fulfill_msg.htlc_id = 1;
6382
6383         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6384
6385         assert!(nodes[0].node.list_channels().is_empty());
6386         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6387         assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6388         check_added_monitors!(nodes[0], 1);
6389         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6390 }
6391
6392 #[test]
6393 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6394         //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.
6395
6396         let chanmon_cfgs = create_chanmon_cfgs(2);
6397         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6398         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6399         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6400         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6401
6402         let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6403
6404         nodes[1].node.claim_funds(our_payment_preimage);
6405         check_added_monitors!(nodes[1], 1);
6406         expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6407
6408         let events = nodes[1].node.get_and_clear_pending_msg_events();
6409         assert_eq!(events.len(), 1);
6410         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6411                 match events[0] {
6412                         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, .. } } => {
6413                                 assert!(update_add_htlcs.is_empty());
6414                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6415                                 assert!(update_fail_htlcs.is_empty());
6416                                 assert!(update_fail_malformed_htlcs.is_empty());
6417                                 assert!(update_fee.is_none());
6418                                 update_fulfill_htlcs[0].clone()
6419                         },
6420                         _ => panic!("Unexpected event"),
6421                 }
6422         };
6423
6424         update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6425
6426         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6427
6428         assert!(nodes[0].node.list_channels().is_empty());
6429         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6430         assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6431         check_added_monitors!(nodes[0], 1);
6432         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6433 }
6434
6435 #[test]
6436 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6437         //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.
6438
6439         let chanmon_cfgs = create_chanmon_cfgs(2);
6440         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6441         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6442         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6443         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6444
6445         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6446         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6447         check_added_monitors!(nodes[0], 1);
6448
6449         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6450         updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6451
6452         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6453         check_added_monitors!(nodes[1], 0);
6454         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6455
6456         let events = nodes[1].node.get_and_clear_pending_msg_events();
6457
6458         let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6459                 match events[0] {
6460                         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, .. } } => {
6461                                 assert!(update_add_htlcs.is_empty());
6462                                 assert!(update_fulfill_htlcs.is_empty());
6463                                 assert!(update_fail_htlcs.is_empty());
6464                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6465                                 assert!(update_fee.is_none());
6466                                 update_fail_malformed_htlcs[0].clone()
6467                         },
6468                         _ => panic!("Unexpected event"),
6469                 }
6470         };
6471         update_msg.failure_code &= !0x8000;
6472         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6473
6474         assert!(nodes[0].node.list_channels().is_empty());
6475         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6476         assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6477         check_added_monitors!(nodes[0], 1);
6478         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6479 }
6480
6481 #[test]
6482 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6483         //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6484         //    * 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.
6485
6486         let chanmon_cfgs = create_chanmon_cfgs(3);
6487         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6488         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6489         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6490         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6491         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6492
6493         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
6494
6495         //First hop
6496         let mut payment_event = {
6497                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6498                 check_added_monitors!(nodes[0], 1);
6499                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6500                 assert_eq!(events.len(), 1);
6501                 SendEvent::from_event(events.remove(0))
6502         };
6503         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6504         check_added_monitors!(nodes[1], 0);
6505         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6506         expect_pending_htlcs_forwardable!(nodes[1]);
6507         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6508         assert_eq!(events_2.len(), 1);
6509         check_added_monitors!(nodes[1], 1);
6510         payment_event = SendEvent::from_event(events_2.remove(0));
6511         assert_eq!(payment_event.msgs.len(), 1);
6512
6513         //Second Hop
6514         payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6515         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6516         check_added_monitors!(nodes[2], 0);
6517         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6518
6519         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6520         assert_eq!(events_3.len(), 1);
6521         let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6522                 match events_3[0] {
6523                         MessageSendEvent::UpdateHTLCs { node_id: _ , updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, ref update_fee, ref commitment_signed } } => {
6524                                 assert!(update_add_htlcs.is_empty());
6525                                 assert!(update_fulfill_htlcs.is_empty());
6526                                 assert!(update_fail_htlcs.is_empty());
6527                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6528                                 assert!(update_fee.is_none());
6529                                 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6530                         },
6531                         _ => panic!("Unexpected event"),
6532                 }
6533         };
6534
6535         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6536
6537         check_added_monitors!(nodes[1], 0);
6538         commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6539         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 }]);
6540         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6541         assert_eq!(events_4.len(), 1);
6542
6543         //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6544         match events_4[0] {
6545                 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, .. } } => {
6546                         assert!(update_add_htlcs.is_empty());
6547                         assert!(update_fulfill_htlcs.is_empty());
6548                         assert_eq!(update_fail_htlcs.len(), 1);
6549                         assert!(update_fail_malformed_htlcs.is_empty());
6550                         assert!(update_fee.is_none());
6551                 },
6552                 _ => panic!("Unexpected event"),
6553         };
6554
6555         check_added_monitors!(nodes[1], 1);
6556 }
6557
6558 #[test]
6559 fn test_channel_failed_after_message_with_badonion_node_perm_bits_set() {
6560         let chanmon_cfgs = create_chanmon_cfgs(3);
6561         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6562         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6563         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6564         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6565         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6566
6567         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100_000);
6568
6569         // First hop
6570         let mut payment_event = {
6571                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6572                 check_added_monitors!(nodes[0], 1);
6573                 SendEvent::from_node(&nodes[0])
6574         };
6575
6576         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6577         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6578         expect_pending_htlcs_forwardable!(nodes[1]);
6579         check_added_monitors!(nodes[1], 1);
6580         payment_event = SendEvent::from_node(&nodes[1]);
6581         assert_eq!(payment_event.msgs.len(), 1);
6582
6583         // Second Hop
6584         payment_event.msgs[0].onion_routing_packet.version = 1; // Trigger an invalid_onion_version error
6585         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6586         check_added_monitors!(nodes[2], 0);
6587         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6588
6589         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6590         assert_eq!(events_3.len(), 1);
6591         match events_3[0] {
6592                 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6593                         let mut update_msg = updates.update_fail_malformed_htlcs[0].clone();
6594                         // Set the NODE bit (BADONION and PERM already set in invalid_onion_version error)
6595                         update_msg.failure_code |= 0x2000;
6596
6597                         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg);
6598                         commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true);
6599                 },
6600                 _ => panic!("Unexpected event"),
6601         }
6602
6603         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
6604                 vec![HTLCDestination::NextHopChannel {
6605                         node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
6606         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6607         assert_eq!(events_4.len(), 1);
6608         check_added_monitors!(nodes[1], 1);
6609
6610         match events_4[0] {
6611                 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6612                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
6613                         commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
6614                 },
6615                 _ => panic!("Unexpected event"),
6616         }
6617
6618         let events_5 = nodes[0].node.get_and_clear_pending_events();
6619         assert_eq!(events_5.len(), 1);
6620
6621         // Expect a PaymentPathFailed event with a ChannelFailure network update for the channel between
6622         // the node originating the error to its next hop.
6623         match events_5[0] {
6624                 Event::PaymentPathFailed { network_update:
6625                         Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent }), error_code, ..
6626                 } => {
6627                         assert_eq!(short_channel_id, chan_2.0.contents.short_channel_id);
6628                         assert!(is_permanent);
6629                         assert_eq!(error_code, Some(0x8000|0x4000|0x2000|4));
6630                 },
6631                 _ => panic!("Unexpected event"),
6632         }
6633
6634         // TODO: Test actual removal of channel from NetworkGraph when it's implemented.
6635 }
6636
6637 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6638         // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6639         // 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
6640         // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6641
6642         let mut chanmon_cfgs = create_chanmon_cfgs(2);
6643         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
6644         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6645         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6646         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6647         let chan =create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6648
6649         let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6650                 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6651
6652         // We route 2 dust-HTLCs between A and B
6653         let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6654         let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6655         route_payment(&nodes[0], &[&nodes[1]], 1000000);
6656
6657         // Cache one local commitment tx as previous
6658         let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6659
6660         // Fail one HTLC to prune it in the will-be-latest-local commitment tx
6661         nodes[1].node.fail_htlc_backwards(&payment_hash_2);
6662         check_added_monitors!(nodes[1], 0);
6663         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
6664         check_added_monitors!(nodes[1], 1);
6665
6666         let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6667         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
6668         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
6669         check_added_monitors!(nodes[0], 1);
6670
6671         // Cache one local commitment tx as lastest
6672         let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6673
6674         let events = nodes[0].node.get_and_clear_pending_msg_events();
6675         match events[0] {
6676                 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
6677                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
6678                 },
6679                 _ => panic!("Unexpected event"),
6680         }
6681         match events[1] {
6682                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
6683                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
6684                 },
6685                 _ => panic!("Unexpected event"),
6686         }
6687
6688         assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
6689         // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
6690         if announce_latest {
6691                 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
6692         } else {
6693                 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
6694         }
6695
6696         check_closed_broadcast!(nodes[0], true);
6697         check_added_monitors!(nodes[0], 1);
6698         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6699
6700         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6701         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6702         let events = nodes[0].node.get_and_clear_pending_events();
6703         // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
6704         assert_eq!(events.len(), 2);
6705         let mut first_failed = false;
6706         for event in events {
6707                 match event {
6708                         Event::PaymentPathFailed { payment_hash, .. } => {
6709                                 if payment_hash == payment_hash_1 {
6710                                         assert!(!first_failed);
6711                                         first_failed = true;
6712                                 } else {
6713                                         assert_eq!(payment_hash, payment_hash_2);
6714                                 }
6715                         }
6716                         _ => panic!("Unexpected event"),
6717                 }
6718         }
6719 }
6720
6721 #[test]
6722 fn test_failure_delay_dust_htlc_local_commitment() {
6723         do_test_failure_delay_dust_htlc_local_commitment(true);
6724         do_test_failure_delay_dust_htlc_local_commitment(false);
6725 }
6726
6727 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
6728         // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
6729         // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
6730         // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
6731         // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
6732         // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
6733         // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
6734
6735         let chanmon_cfgs = create_chanmon_cfgs(3);
6736         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6737         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6738         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6739         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6740
6741         let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6742                 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6743
6744         let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6745         let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6746
6747         let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6748         let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
6749
6750         // We revoked bs_commitment_tx
6751         if revoked {
6752                 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6753                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
6754         }
6755
6756         let mut timeout_tx = Vec::new();
6757         if local {
6758                 // We fail dust-HTLC 1 by broadcast of local commitment tx
6759                 mine_transaction(&nodes[0], &as_commitment_tx[0]);
6760                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6761                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6762                 expect_payment_failed!(nodes[0], dust_hash, false);
6763
6764                 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
6765                 check_closed_broadcast!(nodes[0], true);
6766                 check_added_monitors!(nodes[0], 1);
6767                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6768                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
6769                 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6770                 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
6771                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6772                 mine_transaction(&nodes[0], &timeout_tx[0]);
6773                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6774                 expect_payment_failed!(nodes[0], non_dust_hash, false);
6775         } else {
6776                 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
6777                 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
6778                 check_closed_broadcast!(nodes[0], true);
6779                 check_added_monitors!(nodes[0], 1);
6780                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6781                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6782
6783                 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
6784                 timeout_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().drain(..)
6785                         .filter(|tx| tx.input[0].previous_output.txid == bs_commitment_tx[0].txid()).collect();
6786                 check_spends!(timeout_tx[0], bs_commitment_tx[0]);
6787                 // For both a revoked or non-revoked commitment transaction, after ANTI_REORG_DELAY the
6788                 // dust HTLC should have been failed.
6789                 expect_payment_failed!(nodes[0], dust_hash, false);
6790
6791                 if !revoked {
6792                         assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6793                 } else {
6794                         assert_eq!(timeout_tx[0].lock_time.0, 0);
6795                 }
6796                 // We fail non-dust-HTLC 2 by broadcast of local timeout/revocation-claim tx
6797                 mine_transaction(&nodes[0], &timeout_tx[0]);
6798                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6799                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6800                 expect_payment_failed!(nodes[0], non_dust_hash, false);
6801         }
6802 }
6803
6804 #[test]
6805 fn test_sweep_outbound_htlc_failure_update() {
6806         do_test_sweep_outbound_htlc_failure_update(false, true);
6807         do_test_sweep_outbound_htlc_failure_update(false, false);
6808         do_test_sweep_outbound_htlc_failure_update(true, false);
6809 }
6810
6811 #[test]
6812 fn test_user_configurable_csv_delay() {
6813         // We test our channel constructors yield errors when we pass them absurd csv delay
6814
6815         let mut low_our_to_self_config = UserConfig::default();
6816         low_our_to_self_config.channel_handshake_config.our_to_self_delay = 6;
6817         let mut high_their_to_self_config = UserConfig::default();
6818         high_their_to_self_config.channel_handshake_limits.their_to_self_delay = 100;
6819         let user_cfgs = [Some(high_their_to_self_config.clone()), None];
6820         let chanmon_cfgs = create_chanmon_cfgs(2);
6821         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6822         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
6823         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6824
6825         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
6826         if let Err(error) = Channel::new_outbound(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
6827                 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &channelmanager::provided_init_features(), 1000000, 1000000, 0,
6828                 &low_our_to_self_config, 0, 42)
6829         {
6830                 match error {
6831                         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())); },
6832                         _ => panic!("Unexpected event"),
6833                 }
6834         } else { assert!(false) }
6835
6836         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
6837         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6838         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
6839         open_channel.to_self_delay = 200;
6840         if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
6841                 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &channelmanager::provided_init_features(), &open_channel, 0,
6842                 &low_our_to_self_config, 0, &nodes[0].logger, 42)
6843         {
6844                 match error {
6845                         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()));  },
6846                         _ => panic!("Unexpected event"),
6847                 }
6848         } else { assert!(false); }
6849
6850         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
6851         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6852         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id()));
6853         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
6854         accept_channel.to_self_delay = 200;
6855         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_channel);
6856         let reason_msg;
6857         if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
6858                 match action {
6859                         &ErrorAction::SendErrorMessage { ref msg } => {
6860                                 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()));
6861                                 reason_msg = msg.data.clone();
6862                         },
6863                         _ => { panic!(); }
6864                 }
6865         } else { panic!(); }
6866         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg });
6867
6868         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
6869         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6870         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
6871         open_channel.to_self_delay = 200;
6872         if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
6873                 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &channelmanager::provided_init_features(), &open_channel, 0,
6874                 &high_their_to_self_config, 0, &nodes[0].logger, 42)
6875         {
6876                 match error {
6877                         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())); },
6878                         _ => panic!("Unexpected event"),
6879                 }
6880         } else { assert!(false); }
6881 }
6882
6883 #[test]
6884 fn test_check_htlc_underpaying() {
6885         // Send payment through A -> B but A is maliciously
6886         // sending a probe payment (i.e less than expected value0
6887         // to B, B should refuse payment.
6888
6889         let chanmon_cfgs = create_chanmon_cfgs(2);
6890         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6891         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6892         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6893
6894         // Create some initial channels
6895         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6896
6897         let scorer = test_utils::TestScorer::with_penalty(0);
6898         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
6899         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id()).with_features(channelmanager::provided_invoice_features());
6900         let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None, 10_000, TEST_FINAL_CLTV, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
6901         let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
6902         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200).unwrap();
6903         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6904         check_added_monitors!(nodes[0], 1);
6905
6906         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6907         assert_eq!(events.len(), 1);
6908         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
6909         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6910         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6911
6912         // Note that we first have to wait a random delay before processing the receipt of the HTLC,
6913         // and then will wait a second random delay before failing the HTLC back:
6914         expect_pending_htlcs_forwardable!(nodes[1]);
6915         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
6916
6917         // Node 3 is expecting payment of 100_000 but received 10_000,
6918         // it should fail htlc like we didn't know the preimage.
6919         nodes[1].node.process_pending_htlc_forwards();
6920
6921         let events = nodes[1].node.get_and_clear_pending_msg_events();
6922         assert_eq!(events.len(), 1);
6923         let (update_fail_htlc, commitment_signed) = match events[0] {
6924                 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 } } => {
6925                         assert!(update_add_htlcs.is_empty());
6926                         assert!(update_fulfill_htlcs.is_empty());
6927                         assert_eq!(update_fail_htlcs.len(), 1);
6928                         assert!(update_fail_malformed_htlcs.is_empty());
6929                         assert!(update_fee.is_none());
6930                         (update_fail_htlcs[0].clone(), commitment_signed)
6931                 },
6932                 _ => panic!("Unexpected event"),
6933         };
6934         check_added_monitors!(nodes[1], 1);
6935
6936         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
6937         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
6938
6939         // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
6940         let mut expected_failure_data = (10_000 as u64).to_be_bytes().to_vec();
6941         expected_failure_data.extend_from_slice(&CHAN_CONFIRM_DEPTH.to_be_bytes());
6942         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
6943 }
6944
6945 #[test]
6946 fn test_announce_disable_channels() {
6947         // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
6948         // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
6949
6950         let chanmon_cfgs = create_chanmon_cfgs(2);
6951         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6952         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6953         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6954
6955         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6956         create_announced_chan_between_nodes(&nodes, 1, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6957         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6958
6959         // Disconnect peers
6960         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6961         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6962
6963         nodes[0].node.timer_tick_occurred(); // Enabled -> DisabledStaged
6964         nodes[0].node.timer_tick_occurred(); // DisabledStaged -> Disabled
6965         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
6966         assert_eq!(msg_events.len(), 3);
6967         let mut chans_disabled = HashMap::new();
6968         for e in msg_events {
6969                 match e {
6970                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
6971                                 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
6972                                 // Check that each channel gets updated exactly once
6973                                 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
6974                                         panic!("Generated ChannelUpdate for wrong chan!");
6975                                 }
6976                         },
6977                         _ => panic!("Unexpected event"),
6978                 }
6979         }
6980         // Reconnect peers
6981         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
6982         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6983         assert_eq!(reestablish_1.len(), 3);
6984         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
6985         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6986         assert_eq!(reestablish_2.len(), 3);
6987
6988         // Reestablish chan_1
6989         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6990         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6991         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6992         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6993         // Reestablish chan_2
6994         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
6995         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6996         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
6997         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6998         // Reestablish chan_3
6999         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7000         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7001         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7002         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7003
7004         nodes[0].node.timer_tick_occurred();
7005         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7006         nodes[0].node.timer_tick_occurred();
7007         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7008         assert_eq!(msg_events.len(), 3);
7009         for e in msg_events {
7010                 match e {
7011                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7012                                 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7013                                 match chans_disabled.remove(&msg.contents.short_channel_id) {
7014                                         // Each update should have a higher timestamp than the previous one, replacing
7015                                         // the old one.
7016                                         Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7017                                         None => panic!("Generated ChannelUpdate for wrong chan!"),
7018                                 }
7019                         },
7020                         _ => panic!("Unexpected event"),
7021                 }
7022         }
7023         // Check that each channel gets updated exactly once
7024         assert!(chans_disabled.is_empty());
7025 }
7026
7027 #[test]
7028 fn test_bump_penalty_txn_on_revoked_commitment() {
7029         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7030         // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7031
7032         let chanmon_cfgs = create_chanmon_cfgs(2);
7033         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7034         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7035         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7036
7037         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7038
7039         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7040         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id())
7041                 .with_features(channelmanager::provided_invoice_features());
7042         let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000, 30);
7043         send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7044
7045         let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7046         // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7047         assert_eq!(revoked_txn[0].output.len(), 4);
7048         assert_eq!(revoked_txn[0].input.len(), 1);
7049         assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7050         let revoked_txid = revoked_txn[0].txid();
7051
7052         let mut penalty_sum = 0;
7053         for outp in revoked_txn[0].output.iter() {
7054                 if outp.script_pubkey.is_v0_p2wsh() {
7055                         penalty_sum += outp.value;
7056                 }
7057         }
7058
7059         // Connect blocks to change height_timer range to see if we use right soonest_timelock
7060         let header_114 = connect_blocks(&nodes[1], 14);
7061
7062         // Actually revoke tx by claiming a HTLC
7063         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7064         let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7065         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] });
7066         check_added_monitors!(nodes[1], 1);
7067
7068         // One or more justice tx should have been broadcast, check it
7069         let penalty_1;
7070         let feerate_1;
7071         {
7072                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7073                 assert_eq!(node_txn.len(), 1); // justice tx (broadcasted from ChannelMonitor)
7074                 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7075                 assert_eq!(node_txn[0].output.len(), 1);
7076                 check_spends!(node_txn[0], revoked_txn[0]);
7077                 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7078                 feerate_1 = fee_1 * 1000 / node_txn[0].weight() as u64;
7079                 penalty_1 = node_txn[0].txid();
7080                 node_txn.clear();
7081         };
7082
7083         // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7084         connect_blocks(&nodes[1], 15);
7085         let mut penalty_2 = penalty_1;
7086         let mut feerate_2 = 0;
7087         {
7088                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7089                 assert_eq!(node_txn.len(), 1);
7090                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7091                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7092                         assert_eq!(node_txn[0].output.len(), 1);
7093                         check_spends!(node_txn[0], revoked_txn[0]);
7094                         penalty_2 = node_txn[0].txid();
7095                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7096                         assert_ne!(penalty_2, penalty_1);
7097                         let fee_2 = penalty_sum - node_txn[0].output[0].value;
7098                         feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7099                         // Verify 25% bump heuristic
7100                         assert!(feerate_2 * 100 >= feerate_1 * 125);
7101                         node_txn.clear();
7102                 }
7103         }
7104         assert_ne!(feerate_2, 0);
7105
7106         // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7107         connect_blocks(&nodes[1], 1);
7108         let penalty_3;
7109         let mut feerate_3 = 0;
7110         {
7111                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7112                 assert_eq!(node_txn.len(), 1);
7113                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7114                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7115                         assert_eq!(node_txn[0].output.len(), 1);
7116                         check_spends!(node_txn[0], revoked_txn[0]);
7117                         penalty_3 = node_txn[0].txid();
7118                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7119                         assert_ne!(penalty_3, penalty_2);
7120                         let fee_3 = penalty_sum - node_txn[0].output[0].value;
7121                         feerate_3 = fee_3 * 1000 / node_txn[0].weight() as u64;
7122                         // Verify 25% bump heuristic
7123                         assert!(feerate_3 * 100 >= feerate_2 * 125);
7124                         node_txn.clear();
7125                 }
7126         }
7127         assert_ne!(feerate_3, 0);
7128
7129         nodes[1].node.get_and_clear_pending_events();
7130         nodes[1].node.get_and_clear_pending_msg_events();
7131 }
7132
7133 #[test]
7134 fn test_bump_penalty_txn_on_revoked_htlcs() {
7135         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7136         // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7137
7138         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7139         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7140         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7141         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7142         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7143
7144         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7145         // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7146         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id()).with_features(channelmanager::provided_invoice_features());
7147         let scorer = test_utils::TestScorer::with_penalty(0);
7148         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7149         let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None,
7150                 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7151         let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7152         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id()).with_features(channelmanager::provided_invoice_features());
7153         let route = get_route(&nodes[1].node.get_our_node_id(), &payment_params, &nodes[1].network_graph.read_only(), None,
7154                 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7155         send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7156
7157         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7158         assert_eq!(revoked_local_txn[0].input.len(), 1);
7159         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7160
7161         // Revoke local commitment tx
7162         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7163
7164         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7165         // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7166         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] });
7167         check_closed_broadcast!(nodes[1], true);
7168         check_added_monitors!(nodes[1], 1);
7169         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7170         connect_blocks(&nodes[1], 49); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7171
7172         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
7173         assert_eq!(revoked_htlc_txn.len(), 2);
7174
7175         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7176         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7177         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7178
7179         assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7180         assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7181         assert_eq!(revoked_htlc_txn[1].output.len(), 1);
7182         check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7183
7184         // Broadcast set of revoked txn on A
7185         let hash_128 = connect_blocks(&nodes[0], 40);
7186         let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7187         connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] });
7188         let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7189         connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()] });
7190         let events = nodes[0].node.get_and_clear_pending_events();
7191         expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7192         match events.last().unwrap() {
7193                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7194                 _ => panic!("Unexpected event"),
7195         }
7196         let first;
7197         let feerate_1;
7198         let penalty_txn;
7199         {
7200                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7201                 assert_eq!(node_txn.len(), 4); // 3 penalty txn on revoked commitment tx + 1 penalty tnx on revoked HTLC txn
7202                 // Verify claim tx are spending revoked HTLC txn
7203
7204                 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7205                 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7206                 // which are included in the same block (they are broadcasted because we scan the
7207                 // transactions linearly and generate claims as we go, they likely should be removed in the
7208                 // future).
7209                 assert_eq!(node_txn[0].input.len(), 1);
7210                 check_spends!(node_txn[0], revoked_local_txn[0]);
7211                 assert_eq!(node_txn[1].input.len(), 1);
7212                 check_spends!(node_txn[1], revoked_local_txn[0]);
7213                 assert_eq!(node_txn[2].input.len(), 1);
7214                 check_spends!(node_txn[2], revoked_local_txn[0]);
7215
7216                 // Each of the three justice transactions claim a separate (single) output of the three
7217                 // available, which we check here:
7218                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7219                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7220                 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7221
7222                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7223                 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7224
7225                 // node_txn[3] spends the revoked outputs from the revoked_htlc_txn (which only have one
7226                 // output, checked above).
7227                 assert_eq!(node_txn[3].input.len(), 2);
7228                 assert_eq!(node_txn[3].output.len(), 1);
7229                 check_spends!(node_txn[3], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7230
7231                 first = node_txn[3].txid();
7232                 // Store both feerates for later comparison
7233                 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[3].output[0].value;
7234                 feerate_1 = fee_1 * 1000 / node_txn[3].weight() as u64;
7235                 penalty_txn = vec![node_txn[2].clone()];
7236                 node_txn.clear();
7237         }
7238
7239         // Connect one more block to see if bumped penalty are issued for HTLC txn
7240         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7241         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7242         let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7243         connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() });
7244
7245         // Few more blocks to confirm penalty txn
7246         connect_blocks(&nodes[0], 4);
7247         assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7248         let header_144 = connect_blocks(&nodes[0], 9);
7249         let node_txn = {
7250                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7251                 assert_eq!(node_txn.len(), 1);
7252
7253                 assert_eq!(node_txn[0].input.len(), 2);
7254                 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7255                 // Verify bumped tx is different and 25% bump heuristic
7256                 assert_ne!(first, node_txn[0].txid());
7257                 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7258                 let feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7259                 assert!(feerate_2 * 100 > feerate_1 * 125);
7260                 let txn = vec![node_txn[0].clone()];
7261                 node_txn.clear();
7262                 txn
7263         };
7264         // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7265         let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7266         connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn });
7267         connect_blocks(&nodes[0], 20);
7268         {
7269                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7270                 // We verify than no new transaction has been broadcast because previously
7271                 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7272                 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7273                 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7274                 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7275                 // up bumped justice generation.
7276                 assert_eq!(node_txn.len(), 0);
7277                 node_txn.clear();
7278         }
7279         check_closed_broadcast!(nodes[0], true);
7280         check_added_monitors!(nodes[0], 1);
7281 }
7282
7283 #[test]
7284 fn test_bump_penalty_txn_on_remote_commitment() {
7285         // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7286         // we're able to claim outputs on remote commitment transaction before timelocks expiration
7287
7288         // Create 2 HTLCs
7289         // Provide preimage for one
7290         // Check aggregation
7291
7292         let chanmon_cfgs = create_chanmon_cfgs(2);
7293         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7294         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7295         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7296
7297         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7298         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
7299         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7300
7301         // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7302         let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7303         assert_eq!(remote_txn[0].output.len(), 4);
7304         assert_eq!(remote_txn[0].input.len(), 1);
7305         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7306
7307         // Claim a HTLC without revocation (provide B monitor with preimage)
7308         nodes[1].node.claim_funds(payment_preimage);
7309         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
7310         mine_transaction(&nodes[1], &remote_txn[0]);
7311         check_added_monitors!(nodes[1], 2);
7312         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7313
7314         // One or more claim tx should have been broadcast, check it
7315         let timeout;
7316         let preimage;
7317         let preimage_bump;
7318         let feerate_timeout;
7319         let feerate_preimage;
7320         {
7321                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7322                 // 3 transactions including:
7323                 //   preimage and timeout sweeps from remote commitment + preimage sweep bump
7324                 assert_eq!(node_txn.len(), 3);
7325                 assert_eq!(node_txn[0].input.len(), 1);
7326                 assert_eq!(node_txn[1].input.len(), 1);
7327                 assert_eq!(node_txn[2].input.len(), 1);
7328                 check_spends!(node_txn[0], remote_txn[0]);
7329                 check_spends!(node_txn[1], remote_txn[0]);
7330                 check_spends!(node_txn[2], remote_txn[0]);
7331
7332                 preimage = node_txn[0].txid();
7333                 let index = node_txn[0].input[0].previous_output.vout;
7334                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7335                 feerate_preimage = fee * 1000 / node_txn[0].weight() as u64;
7336
7337                 let (preimage_bump_tx, timeout_tx) = if node_txn[2].input[0].previous_output == node_txn[0].input[0].previous_output {
7338                         (node_txn[2].clone(), node_txn[1].clone())
7339                 } else {
7340                         (node_txn[1].clone(), node_txn[2].clone())
7341                 };
7342
7343                 preimage_bump = preimage_bump_tx;
7344                 check_spends!(preimage_bump, remote_txn[0]);
7345                 assert_eq!(node_txn[0].input[0].previous_output, preimage_bump.input[0].previous_output);
7346
7347                 timeout = timeout_tx.txid();
7348                 let index = timeout_tx.input[0].previous_output.vout;
7349                 let fee = remote_txn[0].output[index as usize].value - timeout_tx.output[0].value;
7350                 feerate_timeout = fee * 1000 / timeout_tx.weight() as u64;
7351
7352                 node_txn.clear();
7353         };
7354         assert_ne!(feerate_timeout, 0);
7355         assert_ne!(feerate_preimage, 0);
7356
7357         // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7358         connect_blocks(&nodes[1], 15);
7359         {
7360                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7361                 assert_eq!(node_txn.len(), 1);
7362                 assert_eq!(node_txn[0].input.len(), 1);
7363                 assert_eq!(preimage_bump.input.len(), 1);
7364                 check_spends!(node_txn[0], remote_txn[0]);
7365                 check_spends!(preimage_bump, remote_txn[0]);
7366
7367                 let index = preimage_bump.input[0].previous_output.vout;
7368                 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
7369                 let new_feerate = fee * 1000 / preimage_bump.weight() as u64;
7370                 assert!(new_feerate * 100 > feerate_timeout * 125);
7371                 assert_ne!(timeout, preimage_bump.txid());
7372
7373                 let index = node_txn[0].input[0].previous_output.vout;
7374                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7375                 let new_feerate = fee * 1000 / node_txn[0].weight() as u64;
7376                 assert!(new_feerate * 100 > feerate_preimage * 125);
7377                 assert_ne!(preimage, node_txn[0].txid());
7378
7379                 node_txn.clear();
7380         }
7381
7382         nodes[1].node.get_and_clear_pending_events();
7383         nodes[1].node.get_and_clear_pending_msg_events();
7384 }
7385
7386 #[test]
7387 fn test_counterparty_raa_skip_no_crash() {
7388         // Previously, if our counterparty sent two RAAs in a row without us having provided a
7389         // commitment transaction, we would have happily carried on and provided them the next
7390         // commitment transaction based on one RAA forward. This would probably eventually have led to
7391         // channel closure, but it would not have resulted in funds loss. Still, our
7392         // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
7393         // check simply that the channel is closed in response to such an RAA, but don't check whether
7394         // we decide to punish our counterparty for revoking their funds (as we don't currently
7395         // implement that).
7396         let chanmon_cfgs = create_chanmon_cfgs(2);
7397         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7398         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7399         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7400         let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
7401
7402         let per_commitment_secret;
7403         let next_per_commitment_point;
7404         {
7405                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
7406                 let mut guard = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
7407                 let keys = guard.channel_by_id.get_mut(&channel_id).unwrap().get_signer();
7408
7409                 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7410
7411                 // Make signer believe we got a counterparty signature, so that it allows the revocation
7412                 keys.get_enforcement_state().last_holder_commitment -= 1;
7413                 per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
7414
7415                 // Must revoke without gaps
7416                 keys.get_enforcement_state().last_holder_commitment -= 1;
7417                 keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
7418
7419                 keys.get_enforcement_state().last_holder_commitment -= 1;
7420                 next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7421                         &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7422         }
7423
7424         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7425                 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
7426         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7427         check_added_monitors!(nodes[1], 1);
7428         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
7429 }
7430
7431 #[test]
7432 fn test_bump_txn_sanitize_tracking_maps() {
7433         // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7434         // verify we clean then right after expiration of ANTI_REORG_DELAY.
7435
7436         let chanmon_cfgs = create_chanmon_cfgs(2);
7437         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7438         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7439         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7440
7441         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7442         // Lock HTLC in both directions
7443         let (payment_preimage_1, _, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000);
7444         let (_, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000);
7445
7446         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7447         assert_eq!(revoked_local_txn[0].input.len(), 1);
7448         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7449
7450         // Revoke local commitment tx
7451         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
7452
7453         // Broadcast set of revoked txn on A
7454         connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
7455         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[0], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
7456         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
7457
7458         mine_transaction(&nodes[0], &revoked_local_txn[0]);
7459         check_closed_broadcast!(nodes[0], true);
7460         check_added_monitors!(nodes[0], 1);
7461         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7462         let penalty_txn = {
7463                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7464                 assert_eq!(node_txn.len(), 3); //ChannelMonitor: justice txn * 3
7465                 check_spends!(node_txn[0], revoked_local_txn[0]);
7466                 check_spends!(node_txn[1], revoked_local_txn[0]);
7467                 check_spends!(node_txn[2], revoked_local_txn[0]);
7468                 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7469                 node_txn.clear();
7470                 penalty_txn
7471         };
7472         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7473         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7474         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7475         {
7476                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
7477                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
7478                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
7479         }
7480 }
7481
7482 #[test]
7483 fn test_pending_claimed_htlc_no_balance_underflow() {
7484         // Tests that if we have a pending outbound HTLC as well as a claimed-but-not-fully-removed
7485         // HTLC we will not underflow when we call `Channel::get_balance_msat()`.
7486         let chanmon_cfgs = create_chanmon_cfgs(2);
7487         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7488         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7489         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7490         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7491
7492         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_010_000);
7493         nodes[1].node.claim_funds(payment_preimage);
7494         expect_payment_claimed!(nodes[1], payment_hash, 1_010_000);
7495         check_added_monitors!(nodes[1], 1);
7496         let fulfill_ev = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7497
7498         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &fulfill_ev.update_fulfill_htlcs[0]);
7499         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
7500         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &fulfill_ev.commitment_signed);
7501         check_added_monitors!(nodes[0], 1);
7502         let (_raa, _cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7503
7504         // At this point nodes[1] has received 1,010k msat (10k msat more than their reserve) and can
7505         // send an HTLC back (though it will go in the holding cell). Send an HTLC back and check we
7506         // can get our balance.
7507
7508         // Get a route from nodes[1] to nodes[0] by getting a route going the other way and then flip
7509         // the public key of the only hop. This works around ChannelDetails not showing the
7510         // almost-claimed HTLC as available balance.
7511         let (mut route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 10_000);
7512         route.payment_params = None; // This is all wrong, but unnecessary
7513         route.paths[0][0].pubkey = nodes[0].node.get_our_node_id();
7514         let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[0]);
7515         nodes[1].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
7516
7517         assert_eq!(nodes[1].node.list_channels()[0].balance_msat, 1_000_000);
7518 }
7519
7520 #[test]
7521 fn test_channel_conf_timeout() {
7522         // Tests that, for inbound channels, we give up on them if the funding transaction does not
7523         // confirm within 2016 blocks, as recommended by BOLT 2.
7524         let chanmon_cfgs = create_chanmon_cfgs(2);
7525         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7526         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7527         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7528
7529         let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7530
7531         // The outbound node should wait forever for confirmation:
7532         // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
7533         // copied here instead of directly referencing the constant.
7534         connect_blocks(&nodes[0], 2016);
7535         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7536
7537         // The inbound node should fail the channel after exactly 2016 blocks
7538         connect_blocks(&nodes[1], 2015);
7539         check_added_monitors!(nodes[1], 0);
7540         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7541
7542         connect_blocks(&nodes[1], 1);
7543         check_added_monitors!(nodes[1], 1);
7544         check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut);
7545         let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
7546         assert_eq!(close_ev.len(), 1);
7547         match close_ev[0] {
7548                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
7549                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7550                         assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
7551                 },
7552                 _ => panic!("Unexpected event"),
7553         }
7554 }
7555
7556 #[test]
7557 fn test_override_channel_config() {
7558         let chanmon_cfgs = create_chanmon_cfgs(2);
7559         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7560         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7561         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7562
7563         // Node0 initiates a channel to node1 using the override config.
7564         let mut override_config = UserConfig::default();
7565         override_config.channel_handshake_config.our_to_self_delay = 200;
7566
7567         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
7568
7569         // Assert the channel created by node0 is using the override config.
7570         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7571         assert_eq!(res.channel_flags, 0);
7572         assert_eq!(res.to_self_delay, 200);
7573 }
7574
7575 #[test]
7576 fn test_override_0msat_htlc_minimum() {
7577         let mut zero_config = UserConfig::default();
7578         zero_config.channel_handshake_config.our_htlc_minimum_msat = 0;
7579         let chanmon_cfgs = create_chanmon_cfgs(2);
7580         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7581         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
7582         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7583
7584         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
7585         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7586         assert_eq!(res.htlc_minimum_msat, 1);
7587
7588         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &res);
7589         let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7590         assert_eq!(res.htlc_minimum_msat, 1);
7591 }
7592
7593 #[test]
7594 fn test_channel_update_has_correct_htlc_maximum_msat() {
7595         // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
7596         // Bolt 7 specifies that if present `htlc_maximum_msat`:
7597         // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
7598         // 90% of the `channel_value`.
7599         // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
7600
7601         let mut config_30_percent = UserConfig::default();
7602         config_30_percent.channel_handshake_config.announced_channel = true;
7603         config_30_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
7604         let mut config_50_percent = UserConfig::default();
7605         config_50_percent.channel_handshake_config.announced_channel = true;
7606         config_50_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
7607         let mut config_95_percent = UserConfig::default();
7608         config_95_percent.channel_handshake_config.announced_channel = true;
7609         config_95_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
7610         let mut config_100_percent = UserConfig::default();
7611         config_100_percent.channel_handshake_config.announced_channel = true;
7612         config_100_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
7613
7614         let chanmon_cfgs = create_chanmon_cfgs(4);
7615         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
7616         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)]);
7617         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
7618
7619         let channel_value_satoshis = 100000;
7620         let channel_value_msat = channel_value_satoshis * 1000;
7621         let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
7622         let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
7623         let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
7624
7625         let (node_0_chan_update, node_1_chan_update, _, _)  = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value_satoshis, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7626         let (node_2_chan_update, node_3_chan_update, _, _)  = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, channel_value_satoshis, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7627
7628         // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
7629         // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
7630         assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, channel_value_50_percent_msat);
7631         // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
7632         // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
7633         assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, channel_value_30_percent_msat);
7634
7635         // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7636         // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
7637         // `channel_value`.
7638         assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7639         // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7640         // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
7641         // `channel_value`.
7642         assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7643 }
7644
7645 #[test]
7646 fn test_manually_accept_inbound_channel_request() {
7647         let mut manually_accept_conf = UserConfig::default();
7648         manually_accept_conf.manually_accept_inbound_channels = true;
7649         let chanmon_cfgs = create_chanmon_cfgs(2);
7650         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7651         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7652         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7653
7654         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7655         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7656
7657         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &res);
7658
7659         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7660         // accepting the inbound channel request.
7661         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7662
7663         let events = nodes[1].node.get_and_clear_pending_events();
7664         match events[0] {
7665                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7666                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
7667                 }
7668                 _ => panic!("Unexpected event"),
7669         }
7670
7671         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7672         assert_eq!(accept_msg_ev.len(), 1);
7673
7674         match accept_msg_ev[0] {
7675                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
7676                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7677                 }
7678                 _ => panic!("Unexpected event"),
7679         }
7680
7681         nodes[1].node.force_close_broadcasting_latest_txn(&temp_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7682
7683         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7684         assert_eq!(close_msg_ev.len(), 1);
7685
7686         let events = nodes[1].node.get_and_clear_pending_events();
7687         match events[0] {
7688                 Event::ChannelClosed { user_channel_id, .. } => {
7689                         assert_eq!(user_channel_id, 23);
7690                 }
7691                 _ => panic!("Unexpected event"),
7692         }
7693 }
7694
7695 #[test]
7696 fn test_manually_reject_inbound_channel_request() {
7697         let mut manually_accept_conf = UserConfig::default();
7698         manually_accept_conf.manually_accept_inbound_channels = true;
7699         let chanmon_cfgs = create_chanmon_cfgs(2);
7700         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7701         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7702         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7703
7704         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7705         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7706
7707         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &res);
7708
7709         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7710         // rejecting the inbound channel request.
7711         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7712
7713         let events = nodes[1].node.get_and_clear_pending_events();
7714         match events[0] {
7715                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7716                         nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7717                 }
7718                 _ => panic!("Unexpected event"),
7719         }
7720
7721         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7722         assert_eq!(close_msg_ev.len(), 1);
7723
7724         match close_msg_ev[0] {
7725                 MessageSendEvent::HandleError { ref node_id, .. } => {
7726                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7727                 }
7728                 _ => panic!("Unexpected event"),
7729         }
7730         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
7731 }
7732
7733 #[test]
7734 fn test_reject_funding_before_inbound_channel_accepted() {
7735         // This tests that when `UserConfig::manually_accept_inbound_channels` is set to true, inbound
7736         // channels must to be manually accepted through `ChannelManager::accept_inbound_channel` by
7737         // the node operator before the counterparty sends a `FundingCreated` message. If a
7738         // `FundingCreated` message is received before the channel is accepted, it should be rejected
7739         // and the channel should be closed.
7740         let mut manually_accept_conf = UserConfig::default();
7741         manually_accept_conf.manually_accept_inbound_channels = true;
7742         let chanmon_cfgs = create_chanmon_cfgs(2);
7743         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7744         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7745         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7746
7747         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7748         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7749         let temp_channel_id = res.temporary_channel_id;
7750
7751         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &res);
7752
7753         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in the `msg_events`.
7754         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7755
7756         // Clear the `Event::OpenChannelRequest` event without responding to the request.
7757         nodes[1].node.get_and_clear_pending_events();
7758
7759         // Get the `AcceptChannel` message of `nodes[1]` without calling
7760         // `ChannelManager::accept_inbound_channel`, which generates a
7761         // `MessageSendEvent::SendAcceptChannel` event. The message is passed to `nodes[0]`
7762         // `handle_accept_channel`, which is required in order for `create_funding_transaction` to
7763         // succeed when `nodes[0]` is passed to it.
7764         let accept_chan_msg = {
7765                 let mut node_1_per_peer_lock;
7766                 let mut node_1_peer_state_lock;
7767                 let channel =  get_channel_ref!(&nodes[1], nodes[0], node_1_per_peer_lock, node_1_peer_state_lock, temp_channel_id);
7768                 channel.get_accept_channel_message()
7769         };
7770         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_chan_msg);
7771
7772         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
7773
7774         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
7775         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
7776
7777         // The `funding_created_msg` should be rejected by `nodes[1]` as it hasn't accepted the channel
7778         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
7779
7780         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7781         assert_eq!(close_msg_ev.len(), 1);
7782
7783         let expected_err = "FundingCreated message received before the channel was accepted";
7784         match close_msg_ev[0] {
7785                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id, } => {
7786                         assert_eq!(msg.channel_id, temp_channel_id);
7787                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7788                         assert_eq!(msg.data, expected_err);
7789                 }
7790                 _ => panic!("Unexpected event"),
7791         }
7792
7793         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
7794 }
7795
7796 #[test]
7797 fn test_can_not_accept_inbound_channel_twice() {
7798         let mut manually_accept_conf = UserConfig::default();
7799         manually_accept_conf.manually_accept_inbound_channels = true;
7800         let chanmon_cfgs = create_chanmon_cfgs(2);
7801         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7802         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7803         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7804
7805         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7806         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7807
7808         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &res);
7809
7810         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7811         // accepting the inbound channel request.
7812         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7813
7814         let events = nodes[1].node.get_and_clear_pending_events();
7815         match events[0] {
7816                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7817                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
7818                         let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
7819                         match api_res {
7820                                 Err(APIError::APIMisuseError { err }) => {
7821                                         assert_eq!(err, "The channel isn't currently awaiting to be accepted.");
7822                                 },
7823                                 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
7824                                 Err(_) => panic!("Unexpected Error"),
7825                         }
7826                 }
7827                 _ => panic!("Unexpected event"),
7828         }
7829
7830         // Ensure that the channel wasn't closed after attempting to accept it twice.
7831         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7832         assert_eq!(accept_msg_ev.len(), 1);
7833
7834         match accept_msg_ev[0] {
7835                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
7836                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7837                 }
7838                 _ => panic!("Unexpected event"),
7839         }
7840 }
7841
7842 #[test]
7843 fn test_can_not_accept_unknown_inbound_channel() {
7844         let chanmon_cfg = create_chanmon_cfgs(2);
7845         let node_cfg = create_node_cfgs(2, &chanmon_cfg);
7846         let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
7847         let nodes = create_network(2, &node_cfg, &node_chanmgr);
7848
7849         let unknown_channel_id = [0; 32];
7850         let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
7851         match api_res {
7852                 Err(APIError::ChannelUnavailable { err }) => {
7853                         assert_eq!(err, format!("Channel with id {} not found for the passed counterparty node_id {}", log_bytes!(unknown_channel_id), nodes[1].node.get_our_node_id()));
7854                 },
7855                 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
7856                 Err(_) => panic!("Unexpected Error"),
7857         }
7858 }
7859
7860 #[test]
7861 fn test_simple_mpp() {
7862         // Simple test of sending a multi-path payment.
7863         let chanmon_cfgs = create_chanmon_cfgs(4);
7864         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
7865         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
7866         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
7867
7868         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).0.contents.short_channel_id;
7869         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features()).0.contents.short_channel_id;
7870         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features()).0.contents.short_channel_id;
7871         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features()).0.contents.short_channel_id;
7872
7873         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
7874         let path = route.paths[0].clone();
7875         route.paths.push(path);
7876         route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
7877         route.paths[0][0].short_channel_id = chan_1_id;
7878         route.paths[0][1].short_channel_id = chan_3_id;
7879         route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
7880         route.paths[1][0].short_channel_id = chan_2_id;
7881         route.paths[1][1].short_channel_id = chan_4_id;
7882         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
7883         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
7884 }
7885
7886 #[test]
7887 fn test_preimage_storage() {
7888         // Simple test of payment preimage storage allowing no client-side storage to claim payments
7889         let chanmon_cfgs = create_chanmon_cfgs(2);
7890         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7891         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7892         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7893
7894         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).0.contents.short_channel_id;
7895
7896         {
7897                 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200).unwrap();
7898                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
7899                 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
7900                 check_added_monitors!(nodes[0], 1);
7901                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7902                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7903                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7904                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7905         }
7906         // Note that after leaving the above scope we have no knowledge of any arguments or return
7907         // values from previous calls.
7908         expect_pending_htlcs_forwardable!(nodes[1]);
7909         let events = nodes[1].node.get_and_clear_pending_events();
7910         assert_eq!(events.len(), 1);
7911         match events[0] {
7912                 Event::PaymentClaimable { ref purpose, .. } => {
7913                         match &purpose {
7914                                 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
7915                                         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
7916                                 },
7917                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
7918                         }
7919                 },
7920                 _ => panic!("Unexpected event"),
7921         }
7922 }
7923
7924 #[test]
7925 #[allow(deprecated)]
7926 fn test_secret_timeout() {
7927         // Simple test of payment secret storage time outs. After
7928         // `create_inbound_payment(_for_hash)_legacy` is removed, this test will be removed as well.
7929         let chanmon_cfgs = create_chanmon_cfgs(2);
7930         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7931         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7932         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7933
7934         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).0.contents.short_channel_id;
7935
7936         let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment_legacy(Some(100_000), 2).unwrap();
7937
7938         // We should fail to register the same payment hash twice, at least until we've connected a
7939         // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
7940         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
7941                 assert_eq!(err, "Duplicate payment hash");
7942         } else { panic!(); }
7943         let mut block = {
7944                 let node_1_blocks = nodes[1].blocks.lock().unwrap();
7945                 Block {
7946                         header: BlockHeader {
7947                                 version: 0x2000000,
7948                                 prev_blockhash: node_1_blocks.last().unwrap().0.block_hash(),
7949                                 merkle_root: TxMerkleNode::all_zeros(),
7950                                 time: node_1_blocks.len() as u32 + 7200, bits: 42, nonce: 42 },
7951                         txdata: vec![],
7952                 }
7953         };
7954         connect_block(&nodes[1], &block);
7955         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
7956                 assert_eq!(err, "Duplicate payment hash");
7957         } else { panic!(); }
7958
7959         // If we then connect the second block, we should be able to register the same payment hash
7960         // again (this time getting a new payment secret).
7961         block.header.prev_blockhash = block.header.block_hash();
7962         block.header.time += 1;
7963         connect_block(&nodes[1], &block);
7964         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2).unwrap();
7965         assert_ne!(payment_secret_1, our_payment_secret);
7966
7967         {
7968                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
7969                 nodes[0].node.send_payment(&route, payment_hash, &Some(our_payment_secret), PaymentId(payment_hash.0)).unwrap();
7970                 check_added_monitors!(nodes[0], 1);
7971                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7972                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7973                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7974                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7975         }
7976         // Note that after leaving the above scope we have no knowledge of any arguments or return
7977         // values from previous calls.
7978         expect_pending_htlcs_forwardable!(nodes[1]);
7979         let events = nodes[1].node.get_and_clear_pending_events();
7980         assert_eq!(events.len(), 1);
7981         match events[0] {
7982                 Event::PaymentClaimable { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret }, .. } => {
7983                         assert!(payment_preimage.is_none());
7984                         assert_eq!(payment_secret, our_payment_secret);
7985                         // We don't actually have the payment preimage with which to claim this payment!
7986                 },
7987                 _ => panic!("Unexpected event"),
7988         }
7989 }
7990
7991 #[test]
7992 fn test_bad_secret_hash() {
7993         // Simple test of unregistered payment hash/invalid payment secret handling
7994         let chanmon_cfgs = create_chanmon_cfgs(2);
7995         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7996         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7997         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7998
7999         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).0.contents.short_channel_id;
8000
8001         let random_payment_hash = PaymentHash([42; 32]);
8002         let random_payment_secret = PaymentSecret([43; 32]);
8003         let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2).unwrap();
8004         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8005
8006         // All the below cases should end up being handled exactly identically, so we macro the
8007         // resulting events.
8008         macro_rules! handle_unknown_invalid_payment_data {
8009                 ($payment_hash: expr) => {
8010                         check_added_monitors!(nodes[0], 1);
8011                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8012                         let payment_event = SendEvent::from_event(events.pop().unwrap());
8013                         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8014                         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8015
8016                         // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8017                         // again to process the pending backwards-failure of the HTLC
8018                         expect_pending_htlcs_forwardable!(nodes[1]);
8019                         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment{ payment_hash: $payment_hash }]);
8020                         check_added_monitors!(nodes[1], 1);
8021
8022                         // We should fail the payment back
8023                         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8024                         match events.pop().unwrap() {
8025                                 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8026                                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8027                                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8028                                 },
8029                                 _ => panic!("Unexpected event"),
8030                         }
8031                 }
8032         }
8033
8034         let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8035         // Error data is the HTLC value (100,000) and current block height
8036         let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8037
8038         // Send a payment with the right payment hash but the wrong payment secret
8039         nodes[0].node.send_payment(&route, our_payment_hash, &Some(random_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
8040         handle_unknown_invalid_payment_data!(our_payment_hash);
8041         expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8042
8043         // Send a payment with a random payment hash, but the right payment secret
8044         nodes[0].node.send_payment(&route, random_payment_hash, &Some(our_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8045         handle_unknown_invalid_payment_data!(random_payment_hash);
8046         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8047
8048         // Send a payment with a random payment hash and random payment secret
8049         nodes[0].node.send_payment(&route, random_payment_hash, &Some(random_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8050         handle_unknown_invalid_payment_data!(random_payment_hash);
8051         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8052 }
8053
8054 #[test]
8055 fn test_update_err_monitor_lockdown() {
8056         // Our monitor will lock update of local commitment transaction if a broadcastion condition
8057         // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8058         // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateStatus
8059         // error.
8060         //
8061         // This scenario may happen in a watchtower setup, where watchtower process a block height
8062         // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8063         // commitment at same time.
8064
8065         let chanmon_cfgs = create_chanmon_cfgs(2);
8066         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8067         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8068         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8069
8070         // Create some initial channel
8071         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8072         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8073
8074         // Rebalance the network to generate htlc in the two directions
8075         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8076
8077         // Route a HTLC from node 0 to node 1 (but don't settle)
8078         let (preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
8079
8080         // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8081         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8082         let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8083         let persister = test_utils::TestPersister::new();
8084         let watchtower = {
8085                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8086                 let mut w = test_utils::TestVecWriter(Vec::new());
8087                 monitor.write(&mut w).unwrap();
8088                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8089                                 &mut io::Cursor::new(&w.0), nodes[0].keys_manager).unwrap().1;
8090                 assert!(new_monitor == *monitor);
8091                 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);
8092                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8093                 watchtower
8094         };
8095         let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8096         let block = Block { header, txdata: vec![] };
8097         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8098         // transaction lock time requirements here.
8099         chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 0));
8100         watchtower.chain_monitor.block_connected(&block, 200);
8101
8102         // Try to update ChannelMonitor
8103         nodes[1].node.claim_funds(preimage);
8104         check_added_monitors!(nodes[1], 1);
8105         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
8106
8107         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8108         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8109         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8110         {
8111                 let mut node_0_per_peer_lock;
8112                 let mut node_0_peer_state_lock;
8113                 let mut channel = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1.2);
8114                 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8115                         assert_eq!(watchtower.chain_monitor.update_channel(outpoint, update.clone()), ChannelMonitorUpdateStatus::PermanentFailure);
8116                         assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, update), ChannelMonitorUpdateStatus::Completed);
8117                 } else { assert!(false); }
8118         }
8119         // Our local monitor is in-sync and hasn't processed yet timeout
8120         check_added_monitors!(nodes[0], 1);
8121         let events = nodes[0].node.get_and_clear_pending_events();
8122         assert_eq!(events.len(), 1);
8123 }
8124
8125 #[test]
8126 fn test_concurrent_monitor_claim() {
8127         // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8128         // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8129         // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8130         // state N+1 confirms. Alice claims output from state N+1.
8131
8132         let chanmon_cfgs = create_chanmon_cfgs(2);
8133         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8134         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8135         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8136
8137         // Create some initial channel
8138         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8139         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8140
8141         // Rebalance the network to generate htlc in the two directions
8142         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8143
8144         // Route a HTLC from node 0 to node 1 (but don't settle)
8145         route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8146
8147         // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8148         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8149         let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8150         let persister = test_utils::TestPersister::new();
8151         let watchtower_alice = {
8152                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8153                 let mut w = test_utils::TestVecWriter(Vec::new());
8154                 monitor.write(&mut w).unwrap();
8155                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8156                                 &mut io::Cursor::new(&w.0), nodes[0].keys_manager).unwrap().1;
8157                 assert!(new_monitor == *monitor);
8158                 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);
8159                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8160                 watchtower
8161         };
8162         let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8163         let block = Block { header, txdata: vec![] };
8164         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8165         // transaction lock time requirements here.
8166         chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize((CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS) as usize, (block.clone(), 0));
8167         watchtower_alice.chain_monitor.block_connected(&block, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8168
8169         // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8170         {
8171                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8172                 assert_eq!(txn.len(), 2);
8173                 txn.clear();
8174         }
8175
8176         // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8177         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8178         let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8179         let persister = test_utils::TestPersister::new();
8180         let watchtower_bob = {
8181                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8182                 let mut w = test_utils::TestVecWriter(Vec::new());
8183                 monitor.write(&mut w).unwrap();
8184                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8185                                 &mut io::Cursor::new(&w.0), nodes[0].keys_manager).unwrap().1;
8186                 assert!(new_monitor == *monitor);
8187                 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);
8188                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8189                 watchtower
8190         };
8191         let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8192         watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8193
8194         // Route another payment to generate another update with still previous HTLC pending
8195         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8196         {
8197                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
8198         }
8199         check_added_monitors!(nodes[1], 1);
8200
8201         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8202         assert_eq!(updates.update_add_htlcs.len(), 1);
8203         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8204         {
8205                 let mut node_0_per_peer_lock;
8206                 let mut node_0_peer_state_lock;
8207                 let mut channel = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1.2);
8208                 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8209                         // Watchtower Alice should already have seen the block and reject the update
8210                         assert_eq!(watchtower_alice.chain_monitor.update_channel(outpoint, update.clone()), ChannelMonitorUpdateStatus::PermanentFailure);
8211                         assert_eq!(watchtower_bob.chain_monitor.update_channel(outpoint, update.clone()), ChannelMonitorUpdateStatus::Completed);
8212                         assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, update), ChannelMonitorUpdateStatus::Completed);
8213                 } else { assert!(false); }
8214         }
8215         // Our local monitor is in-sync and hasn't processed yet timeout
8216         check_added_monitors!(nodes[0], 1);
8217
8218         //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8219         let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8220         watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8221
8222         // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8223         let bob_state_y;
8224         {
8225                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8226                 assert_eq!(txn.len(), 2);
8227                 bob_state_y = txn[0].clone();
8228                 txn.clear();
8229         };
8230
8231         // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8232         let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8233         watchtower_alice.chain_monitor.block_connected(&Block { header, txdata: vec![bob_state_y.clone()] }, CHAN_CONFIRM_DEPTH + 2 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8234         {
8235                 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8236                 assert_eq!(htlc_txn.len(), 1);
8237                 check_spends!(htlc_txn[0], bob_state_y);
8238         }
8239 }
8240
8241 #[test]
8242 fn test_pre_lockin_no_chan_closed_update() {
8243         // Test that if a peer closes a channel in response to a funding_created message we don't
8244         // generate a channel update (as the channel cannot appear on chain without a funding_signed
8245         // message).
8246         //
8247         // Doing so would imply a channel monitor update before the initial channel monitor
8248         // registration, violating our API guarantees.
8249         //
8250         // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8251         // then opening a second channel with the same funding output as the first (which is not
8252         // rejected because the first channel does not exist in the ChannelManager) and closing it
8253         // before receiving funding_signed.
8254         let chanmon_cfgs = create_chanmon_cfgs(2);
8255         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8256         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8257         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8258
8259         // Create an initial channel
8260         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8261         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8262         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_chan_msg);
8263         let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8264         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_chan_msg);
8265
8266         // Move the first channel through the funding flow...
8267         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8268
8269         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8270         check_added_monitors!(nodes[0], 0);
8271
8272         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8273         let channel_id = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8274         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8275         assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8276         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "Hi".to_string() }, true);
8277 }
8278
8279 #[test]
8280 fn test_htlc_no_detection() {
8281         // This test is a mutation to underscore the detection logic bug we had
8282         // before #653. HTLC value routed is above the remaining balance, thus
8283         // inverting HTLC and `to_remote` output. HTLC will come second and
8284         // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8285         // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8286         // outputs order detection for correct spending children filtring.
8287
8288         let chanmon_cfgs = create_chanmon_cfgs(2);
8289         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8290         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8291         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8292
8293         // Create some initial channels
8294         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8295
8296         send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8297         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8298         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8299         assert_eq!(local_txn[0].input.len(), 1);
8300         assert_eq!(local_txn[0].output.len(), 3);
8301         check_spends!(local_txn[0], chan_1.3);
8302
8303         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8304         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8305         connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] });
8306         // We deliberately connect the local tx twice as this should provoke a failure calling
8307         // this test before #653 fix.
8308         chain::Listen::block_connected(&nodes[0].chain_monitor.chain_monitor, &Block { header, txdata: vec![local_txn[0].clone()] }, nodes[0].best_block_info().1 + 1);
8309         check_closed_broadcast!(nodes[0], true);
8310         check_added_monitors!(nodes[0], 1);
8311         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8312         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1);
8313
8314         let htlc_timeout = {
8315                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8316                 assert_eq!(node_txn.len(), 1);
8317                 assert_eq!(node_txn[0].input.len(), 1);
8318                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8319                 check_spends!(node_txn[0], local_txn[0]);
8320                 node_txn[0].clone()
8321         };
8322
8323         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8324         connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] });
8325         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8326         expect_payment_failed!(nodes[0], our_payment_hash, false);
8327 }
8328
8329 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8330         // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8331         // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8332         // Carol, Alice would be the upstream node, and Carol the downstream.)
8333         //
8334         // Steps of the test:
8335         // 1) Alice sends a HTLC to Carol through Bob.
8336         // 2) Carol doesn't settle the HTLC.
8337         // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8338         // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8339         // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8340         //    but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8341         // 5) Carol release the preimage to Bob off-chain.
8342         // 6) Bob claims the offered output on the broadcasted commitment.
8343         let chanmon_cfgs = create_chanmon_cfgs(3);
8344         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8345         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8346         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8347
8348         // Create some initial channels
8349         let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8350         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8351
8352         // Steps (1) and (2):
8353         // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8354         let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
8355
8356         // Check that Alice's commitment transaction now contains an output for this HTLC.
8357         let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8358         check_spends!(alice_txn[0], chan_ab.3);
8359         assert_eq!(alice_txn[0].output.len(), 2);
8360         check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8361         assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8362         assert_eq!(alice_txn.len(), 2);
8363
8364         // Steps (3) and (4):
8365         // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8366         // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8367         let mut force_closing_node = 0; // Alice force-closes
8368         let mut counterparty_node = 1; // Bob if Alice force-closes
8369
8370         // Bob force-closes
8371         if !broadcast_alice {
8372                 force_closing_node = 1;
8373                 counterparty_node = 0;
8374         }
8375         nodes[force_closing_node].node.force_close_broadcasting_latest_txn(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id()).unwrap();
8376         check_closed_broadcast!(nodes[force_closing_node], true);
8377         check_added_monitors!(nodes[force_closing_node], 1);
8378         check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
8379         if go_onchain_before_fulfill {
8380                 let txn_to_broadcast = match broadcast_alice {
8381                         true => alice_txn.clone(),
8382                         false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8383                 };
8384                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
8385                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8386                 if broadcast_alice {
8387                         check_closed_broadcast!(nodes[1], true);
8388                         check_added_monitors!(nodes[1], 1);
8389                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8390                 }
8391         }
8392
8393         // Step (5):
8394         // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8395         // process of removing the HTLC from their commitment transactions.
8396         nodes[2].node.claim_funds(payment_preimage);
8397         check_added_monitors!(nodes[2], 1);
8398         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
8399
8400         let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8401         assert!(carol_updates.update_add_htlcs.is_empty());
8402         assert!(carol_updates.update_fail_htlcs.is_empty());
8403         assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8404         assert!(carol_updates.update_fee.is_none());
8405         assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8406
8407         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8408         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false, false);
8409         // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8410         if !go_onchain_before_fulfill && broadcast_alice {
8411                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8412                 assert_eq!(events.len(), 1);
8413                 match events[0] {
8414                         MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8415                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8416                         },
8417                         _ => panic!("Unexpected event"),
8418                 };
8419         }
8420         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8421         // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8422         // Carol<->Bob's updated commitment transaction info.
8423         check_added_monitors!(nodes[1], 2);
8424
8425         let events = nodes[1].node.get_and_clear_pending_msg_events();
8426         assert_eq!(events.len(), 2);
8427         let bob_revocation = match events[0] {
8428                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8429                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8430                         (*msg).clone()
8431                 },
8432                 _ => panic!("Unexpected event"),
8433         };
8434         let bob_updates = match events[1] {
8435                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8436                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8437                         (*updates).clone()
8438                 },
8439                 _ => panic!("Unexpected event"),
8440         };
8441
8442         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8443         check_added_monitors!(nodes[2], 1);
8444         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8445         check_added_monitors!(nodes[2], 1);
8446
8447         let events = nodes[2].node.get_and_clear_pending_msg_events();
8448         assert_eq!(events.len(), 1);
8449         let carol_revocation = match events[0] {
8450                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8451                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8452                         (*msg).clone()
8453                 },
8454                 _ => panic!("Unexpected event"),
8455         };
8456         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8457         check_added_monitors!(nodes[1], 1);
8458
8459         // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8460         // here's where we put said channel's commitment tx on-chain.
8461         let mut txn_to_broadcast = alice_txn.clone();
8462         if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8463         if !go_onchain_before_fulfill {
8464                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
8465                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8466                 // If Bob was the one to force-close, he will have already passed these checks earlier.
8467                 if broadcast_alice {
8468                         check_closed_broadcast!(nodes[1], true);
8469                         check_added_monitors!(nodes[1], 1);
8470                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8471                 }
8472                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8473                 if broadcast_alice {
8474                         assert_eq!(bob_txn.len(), 1);
8475                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
8476                 } else {
8477                         assert_eq!(bob_txn.len(), 2);
8478                         check_spends!(bob_txn[0], chan_ab.3);
8479                 }
8480         }
8481
8482         // Step (6):
8483         // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8484         // broadcasted commitment transaction.
8485         {
8486                 let script_weight = match broadcast_alice {
8487                         true => OFFERED_HTLC_SCRIPT_WEIGHT,
8488                         false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8489                 };
8490                 // If Alice force-closed, Bob only broadcasts a HTLC-output-claiming transaction. Otherwise,
8491                 // Bob force-closed and broadcasts the commitment transaction along with a
8492                 // HTLC-output-claiming transaction.
8493                 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8494                 if broadcast_alice {
8495                         assert_eq!(bob_txn.len(), 1);
8496                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
8497                         assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8498                 } else {
8499                         assert_eq!(bob_txn.len(), 2);
8500                         check_spends!(bob_txn[1], txn_to_broadcast[0]);
8501                         assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8502                 }
8503         }
8504 }
8505
8506 #[test]
8507 fn test_onchain_htlc_settlement_after_close() {
8508         do_test_onchain_htlc_settlement_after_close(true, true);
8509         do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8510         do_test_onchain_htlc_settlement_after_close(true, false);
8511         do_test_onchain_htlc_settlement_after_close(false, false);
8512 }
8513
8514 #[test]
8515 fn test_duplicate_temporary_channel_id_from_different_peers() {
8516         // Tests that we can accept two different `OpenChannel` requests with the same
8517         // `temporary_channel_id`, as long as they are from different peers.
8518         let chanmon_cfgs = create_chanmon_cfgs(3);
8519         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8520         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8521         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8522
8523         // Create an first channel channel
8524         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8525         let mut open_chan_msg_chan_1_0 = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8526
8527         // Create an second channel
8528         nodes[2].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 43, None).unwrap();
8529         let mut open_chan_msg_chan_2_0 = get_event_msg!(nodes[2], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8530
8531         // Modify the `OpenChannel` from `nodes[2]` to `nodes[0]` to ensure that it uses the same
8532         // `temporary_channel_id` as the `OpenChannel` from nodes[1] to nodes[0].
8533         open_chan_msg_chan_2_0.temporary_channel_id = open_chan_msg_chan_1_0.temporary_channel_id;
8534
8535         // Assert that `nodes[0]` can accept both `OpenChannel` requests, even though they use the same
8536         // `temporary_channel_id` as they are from different peers.
8537         nodes[0].node.handle_open_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &open_chan_msg_chan_1_0);
8538         {
8539                 let events = nodes[0].node.get_and_clear_pending_msg_events();
8540                 assert_eq!(events.len(), 1);
8541                 match &events[0] {
8542                         MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8543                                 assert_eq!(node_id, &nodes[1].node.get_our_node_id());
8544                                 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8545                         },
8546                         _ => panic!("Unexpected event"),
8547                 }
8548         }
8549
8550         nodes[0].node.handle_open_channel(&nodes[2].node.get_our_node_id(), channelmanager::provided_init_features(), &open_chan_msg_chan_2_0);
8551         {
8552                 let events = nodes[0].node.get_and_clear_pending_msg_events();
8553                 assert_eq!(events.len(), 1);
8554                 match &events[0] {
8555                         MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8556                                 assert_eq!(node_id, &nodes[2].node.get_our_node_id());
8557                                 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8558                         },
8559                         _ => panic!("Unexpected event"),
8560                 }
8561         }
8562 }
8563
8564 #[test]
8565 fn test_duplicate_chan_id() {
8566         // Test that if a given peer tries to open a channel with the same channel_id as one that is
8567         // already open we reject it and keep the old channel.
8568         //
8569         // Previously, full_stack_target managed to figure out that if you tried to open two channels
8570         // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8571         // the existing channel when we detect the duplicate new channel, screwing up our monitor
8572         // updating logic for the existing channel.
8573         let chanmon_cfgs = create_chanmon_cfgs(2);
8574         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8575         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8576         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8577
8578         // Create an initial channel
8579         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8580         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8581         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_chan_msg);
8582         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id()));
8583
8584         // Try to create a second channel with the same temporary_channel_id as the first and check
8585         // that it is rejected.
8586         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_chan_msg);
8587         {
8588                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8589                 assert_eq!(events.len(), 1);
8590                 match events[0] {
8591                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8592                                 // Technically, at this point, nodes[1] would be justified in thinking both the
8593                                 // first (valid) and second (invalid) channels are closed, given they both have
8594                                 // the same non-temporary channel_id. However, currently we do not, so we just
8595                                 // move forward with it.
8596                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8597                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8598                         },
8599                         _ => panic!("Unexpected event"),
8600                 }
8601         }
8602
8603         // Move the first channel through the funding flow...
8604         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8605
8606         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8607         check_added_monitors!(nodes[0], 0);
8608
8609         let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8610         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8611         {
8612                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
8613                 assert_eq!(added_monitors.len(), 1);
8614                 assert_eq!(added_monitors[0].0, funding_output);
8615                 added_monitors.clear();
8616         }
8617         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8618
8619         let funding_outpoint = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
8620         let channel_id = funding_outpoint.to_channel_id();
8621
8622         // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
8623         // temporary one).
8624
8625         // First try to open a second channel with a temporary channel id equal to the txid-based one.
8626         // Technically this is allowed by the spec, but we don't support it and there's little reason
8627         // to. Still, it shouldn't cause any other issues.
8628         open_chan_msg.temporary_channel_id = channel_id;
8629         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_chan_msg);
8630         {
8631                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8632                 assert_eq!(events.len(), 1);
8633                 match events[0] {
8634                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8635                                 // Technically, at this point, nodes[1] would be justified in thinking both
8636                                 // channels are closed, but currently we do not, so we just move forward with it.
8637                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8638                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8639                         },
8640                         _ => panic!("Unexpected event"),
8641                 }
8642         }
8643
8644         // Now try to create a second channel which has a duplicate funding output.
8645         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8646         let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8647         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_chan_2_msg);
8648         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id()));
8649         create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
8650
8651         let funding_created = {
8652                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
8653                 let mut a_peer_state = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
8654                 // Once we call `get_outbound_funding_created` the channel has a duplicate channel_id as
8655                 // another channel in the ChannelManager - an invalid state. Thus, we'd panic later when we
8656                 // try to create another channel. Instead, we drop the channel entirely here (leaving the
8657                 // channelmanager in a possibly nonsense state instead).
8658                 let mut as_chan = a_peer_state.channel_by_id.remove(&open_chan_2_msg.temporary_channel_id).unwrap();
8659                 let logger = test_utils::TestLogger::new();
8660                 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
8661         };
8662         check_added_monitors!(nodes[0], 0);
8663         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
8664         // At this point we'll try to add a duplicate channel monitor, which will be rejected, but
8665         // still needs to be cleared here.
8666         check_added_monitors!(nodes[1], 1);
8667
8668         // ...still, nodes[1] will reject the duplicate channel.
8669         {
8670                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8671                 assert_eq!(events.len(), 1);
8672                 match events[0] {
8673                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8674                                 // Technically, at this point, nodes[1] would be justified in thinking both
8675                                 // channels are closed, but currently we do not, so we just move forward with it.
8676                                 assert_eq!(msg.channel_id, channel_id);
8677                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8678                         },
8679                         _ => panic!("Unexpected event"),
8680                 }
8681         }
8682
8683         // finally, finish creating the original channel and send a payment over it to make sure
8684         // everything is functional.
8685         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
8686         {
8687                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
8688                 assert_eq!(added_monitors.len(), 1);
8689                 assert_eq!(added_monitors[0].0, funding_output);
8690                 added_monitors.clear();
8691         }
8692
8693         let events_4 = nodes[0].node.get_and_clear_pending_events();
8694         assert_eq!(events_4.len(), 0);
8695         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
8696         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
8697
8698         let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
8699         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
8700         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
8701
8702         send_payment(&nodes[0], &[&nodes[1]], 8000000);
8703 }
8704
8705 #[test]
8706 fn test_error_chans_closed() {
8707         // Test that we properly handle error messages, closing appropriate channels.
8708         //
8709         // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
8710         // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
8711         // we can test various edge cases around it to ensure we don't regress.
8712         let chanmon_cfgs = create_chanmon_cfgs(3);
8713         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8714         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8715         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8716
8717         // Create some initial channels
8718         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8719         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8720         let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8721
8722         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8723         assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
8724         assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
8725
8726         // Closing a channel from a different peer has no effect
8727         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
8728         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8729
8730         // Closing one channel doesn't impact others
8731         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
8732         check_added_monitors!(nodes[0], 1);
8733         check_closed_broadcast!(nodes[0], false);
8734         check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
8735         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
8736         assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
8737         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);
8738         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);
8739
8740         // A null channel ID should close all channels
8741         let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8742         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
8743         check_added_monitors!(nodes[0], 2);
8744         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
8745         let events = nodes[0].node.get_and_clear_pending_msg_events();
8746         assert_eq!(events.len(), 2);
8747         match events[0] {
8748                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8749                         assert_eq!(msg.contents.flags & 2, 2);
8750                 },
8751                 _ => panic!("Unexpected event"),
8752         }
8753         match events[1] {
8754                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8755                         assert_eq!(msg.contents.flags & 2, 2);
8756                 },
8757                 _ => panic!("Unexpected event"),
8758         }
8759         // Note that at this point users of a standard PeerHandler will end up calling
8760         // peer_disconnected with no_connection_possible set to false, duplicating the
8761         // close-all-channels logic. That's OK, we don't want to end up not force-closing channels for
8762         // users with their own peer handling logic. We duplicate the call here, however.
8763         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8764         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
8765
8766         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
8767         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8768         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
8769 }
8770
8771 #[test]
8772 fn test_invalid_funding_tx() {
8773         // Test that we properly handle invalid funding transactions sent to us from a peer.
8774         //
8775         // Previously, all other major lightning implementations had failed to properly sanitize
8776         // funding transactions from their counterparties, leading to a multi-implementation critical
8777         // security vulnerability (though we always sanitized properly, we've previously had
8778         // un-released crashes in the sanitization process).
8779         //
8780         // Further, if the funding transaction is consensus-valid, confirms, and is later spent, we'd
8781         // previously have crashed in `ChannelMonitor` even though we closed the channel as bogus and
8782         // gave up on it. We test this here by generating such a transaction.
8783         let chanmon_cfgs = create_chanmon_cfgs(2);
8784         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8785         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8786         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8787
8788         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
8789         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id()));
8790         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id()));
8791
8792         let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
8793
8794         // Create a witness program which can be spent by a 4-empty-stack-elements witness and which is
8795         // 136 bytes long. This matches our "accepted HTLC preimage spend" matching, previously causing
8796         // a panic as we'd try to extract a 32 byte preimage from a witness element without checking
8797         // its length.
8798         let mut wit_program: Vec<u8> = channelmonitor::deliberately_bogus_accepted_htlc_witness_program();
8799         let wit_program_script: Script = wit_program.into();
8800         for output in tx.output.iter_mut() {
8801                 // Make the confirmed funding transaction have a bogus script_pubkey
8802                 output.script_pubkey = Script::new_v0_p2wsh(&wit_program_script.wscript_hash());
8803         }
8804
8805         nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
8806         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()));
8807         check_added_monitors!(nodes[1], 1);
8808
8809         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()));
8810         check_added_monitors!(nodes[0], 1);
8811
8812         let events_1 = nodes[0].node.get_and_clear_pending_events();
8813         assert_eq!(events_1.len(), 0);
8814
8815         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
8816         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
8817         nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
8818
8819         let expected_err = "funding tx had wrong script/value or output index";
8820         confirm_transaction_at(&nodes[1], &tx, 1);
8821         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
8822         check_added_monitors!(nodes[1], 1);
8823         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
8824         assert_eq!(events_2.len(), 1);
8825         if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
8826                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8827                 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
8828                         assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
8829                 } else { panic!(); }
8830         } else { panic!(); }
8831         assert_eq!(nodes[1].node.list_channels().len(), 0);
8832
8833         // Now confirm a spend of the (bogus) funding transaction. As long as the witness is 5 elements
8834         // long the ChannelMonitor will try to read 32 bytes from the second-to-last element, panicing
8835         // as its not 32 bytes long.
8836         let mut spend_tx = Transaction {
8837                 version: 2i32, lock_time: PackedLockTime::ZERO,
8838                 input: tx.output.iter().enumerate().map(|(idx, _)| TxIn {
8839                         previous_output: BitcoinOutPoint {
8840                                 txid: tx.txid(),
8841                                 vout: idx as u32,
8842                         },
8843                         script_sig: Script::new(),
8844                         sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
8845                         witness: Witness::from_vec(channelmonitor::deliberately_bogus_accepted_htlc_witness())
8846                 }).collect(),
8847                 output: vec![TxOut {
8848                         value: 1000,
8849                         script_pubkey: Script::new(),
8850                 }]
8851         };
8852         check_spends!(spend_tx, tx);
8853         mine_transaction(&nodes[1], &spend_tx);
8854 }
8855
8856 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
8857         // In the first version of the chain::Confirm interface, after a refactor was made to not
8858         // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
8859         // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
8860         // `best_block_updated` is at height N, and a transaction output which we wish to spend at
8861         // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
8862         // spending transaction until height N+1 (or greater). This was due to the way
8863         // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
8864         // spending transaction at the height the input transaction was confirmed at, not whether we
8865         // should broadcast a spending transaction at the current height.
8866         // A second, similar, issue involved failing HTLCs backwards - because we only provided the
8867         // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
8868         // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
8869         // until we learned about an additional block.
8870         //
8871         // As an additional check, if `test_height_before_timelock` is set, we instead test that we
8872         // aren't broadcasting transactions too early (ie not broadcasting them at all).
8873         let chanmon_cfgs = create_chanmon_cfgs(3);
8874         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8875         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8876         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8877         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
8878
8879         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8880         let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8881         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
8882         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
8883         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
8884
8885         nodes[1].node.force_close_broadcasting_latest_txn(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
8886         check_closed_broadcast!(nodes[1], true);
8887         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
8888         check_added_monitors!(nodes[1], 1);
8889         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
8890         assert_eq!(node_txn.len(), 1);
8891
8892         let conf_height = nodes[1].best_block_info().1;
8893         if !test_height_before_timelock {
8894                 connect_blocks(&nodes[1], 24 * 6);
8895         }
8896         nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
8897                 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
8898         if test_height_before_timelock {
8899                 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
8900                 // generate any events or broadcast any transactions
8901                 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
8902                 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
8903         } else {
8904                 // We should broadcast an HTLC transaction spending our funding transaction first
8905                 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
8906                 assert_eq!(spending_txn.len(), 2);
8907                 assert_eq!(spending_txn[0], node_txn[0]);
8908                 check_spends!(spending_txn[1], node_txn[0]);
8909                 // We should also generate a SpendableOutputs event with the to_self output (as its
8910                 // timelock is up).
8911                 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
8912                 assert_eq!(descriptor_spend_txn.len(), 1);
8913
8914                 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
8915                 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
8916                 // additional block built on top of the current chain.
8917                 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
8918                         &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
8919                 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 }]);
8920                 check_added_monitors!(nodes[1], 1);
8921
8922                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8923                 assert!(updates.update_add_htlcs.is_empty());
8924                 assert!(updates.update_fulfill_htlcs.is_empty());
8925                 assert_eq!(updates.update_fail_htlcs.len(), 1);
8926                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8927                 assert!(updates.update_fee.is_none());
8928                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
8929                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
8930                 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
8931         }
8932 }
8933
8934 #[test]
8935 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
8936         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
8937         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
8938 }
8939
8940 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
8941         let chanmon_cfgs = create_chanmon_cfgs(2);
8942         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8943         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8944         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8945
8946         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8947
8948         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
8949                 .with_features(channelmanager::provided_invoice_features());
8950         let route = get_route!(nodes[0], payment_params, 10_000, TEST_FINAL_CLTV).unwrap();
8951
8952         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
8953
8954         {
8955                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
8956                 check_added_monitors!(nodes[0], 1);
8957                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8958                 assert_eq!(events.len(), 1);
8959                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8960                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8961                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8962         }
8963         expect_pending_htlcs_forwardable!(nodes[1]);
8964         expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
8965
8966         {
8967                 // Note that we use a different PaymentId here to allow us to duplicativly pay
8968                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_secret.0)).unwrap();
8969                 check_added_monitors!(nodes[0], 1);
8970                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8971                 assert_eq!(events.len(), 1);
8972                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8973                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8974                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8975                 // At this point, nodes[1] would notice it has too much value for the payment. It will
8976                 // assume the second is a privacy attack (no longer particularly relevant
8977                 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
8978                 // the first HTLC delivered above.
8979         }
8980
8981         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
8982         nodes[1].node.process_pending_htlc_forwards();
8983
8984         if test_for_second_fail_panic {
8985                 // Now we go fail back the first HTLC from the user end.
8986                 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
8987
8988                 let expected_destinations = vec![
8989                         HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
8990                         HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
8991                 ];
8992                 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1],  expected_destinations);
8993                 nodes[1].node.process_pending_htlc_forwards();
8994
8995                 check_added_monitors!(nodes[1], 1);
8996                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8997                 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
8998
8999                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9000                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9001                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9002
9003                 let failure_events = nodes[0].node.get_and_clear_pending_events();
9004                 assert_eq!(failure_events.len(), 2);
9005                 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9006                 if let Event::PaymentPathFailed { .. } = failure_events[1] {} else { panic!(); }
9007         } else {
9008                 // Let the second HTLC fail and claim the first
9009                 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9010                 nodes[1].node.process_pending_htlc_forwards();
9011
9012                 check_added_monitors!(nodes[1], 1);
9013                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9014                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9015                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9016
9017                 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9018
9019                 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9020         }
9021 }
9022
9023 #[test]
9024 fn test_dup_htlc_second_fail_panic() {
9025         // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9026         // value for the payment, we'd fail back both HTLCs after generating a `PaymentClaimable` event.
9027         // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9028         // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9029         do_test_dup_htlc_second_rejected(true);
9030 }
9031
9032 #[test]
9033 fn test_dup_htlc_second_rejected() {
9034         // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9035         // simply reject the second HTLC but are still able to claim the first HTLC.
9036         do_test_dup_htlc_second_rejected(false);
9037 }
9038
9039 #[test]
9040 fn test_inconsistent_mpp_params() {
9041         // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9042         // such HTLC and allow the second to stay.
9043         let chanmon_cfgs = create_chanmon_cfgs(4);
9044         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9045         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9046         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9047
9048         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9049         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9050         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9051         let chan_2_3 =create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9052
9053         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id())
9054                 .with_features(channelmanager::provided_invoice_features());
9055         let mut route = get_route!(nodes[0], payment_params, 15_000_000, TEST_FINAL_CLTV).unwrap();
9056         assert_eq!(route.paths.len(), 2);
9057         route.paths.sort_by(|path_a, _| {
9058                 // Sort the path so that the path through nodes[1] comes first
9059                 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
9060                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9061         });
9062         let payment_params_opt = Some(payment_params);
9063
9064         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9065
9066         let cur_height = nodes[0].best_block_info().1;
9067         let payment_id = PaymentId([42; 32]);
9068
9069         let session_privs = {
9070                 // We create a fake route here so that we start with three pending HTLCs, which we'll
9071                 // ultimately have, just not right away.
9072                 let mut dup_route = route.clone();
9073                 dup_route.paths.push(route.paths[1].clone());
9074                 nodes[0].node.test_add_new_pending_payment(our_payment_hash, Some(our_payment_secret), payment_id, &dup_route).unwrap()
9075         };
9076         {
9077                 nodes[0].node.send_payment_along_path(&route.paths[0], &payment_params_opt, &our_payment_hash, &Some(our_payment_secret), 15_000_000, cur_height, payment_id, &None, session_privs[0]).unwrap();
9078                 check_added_monitors!(nodes[0], 1);
9079
9080                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9081                 assert_eq!(events.len(), 1);
9082                 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9083         }
9084         assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9085
9086         {
9087                 nodes[0].node.send_payment_along_path(&route.paths[1], &payment_params_opt, &our_payment_hash, &Some(our_payment_secret), 14_000_000, cur_height, payment_id, &None, session_privs[1]).unwrap();
9088                 check_added_monitors!(nodes[0], 1);
9089
9090                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9091                 assert_eq!(events.len(), 1);
9092                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9093
9094                 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9095                 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9096
9097                 expect_pending_htlcs_forwardable!(nodes[2]);
9098                 check_added_monitors!(nodes[2], 1);
9099
9100                 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9101                 assert_eq!(events.len(), 1);
9102                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9103
9104                 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9105                 check_added_monitors!(nodes[3], 0);
9106                 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9107
9108                 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9109                 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9110                 // post-payment_secrets) and fail back the new HTLC.
9111         }
9112         expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9113         nodes[3].node.process_pending_htlc_forwards();
9114         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9115         nodes[3].node.process_pending_htlc_forwards();
9116
9117         check_added_monitors!(nodes[3], 1);
9118
9119         let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9120         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9121         commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9122
9123         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 }]);
9124         check_added_monitors!(nodes[2], 1);
9125
9126         let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9127         nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9128         commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9129
9130         expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9131
9132         nodes[0].node.send_payment_along_path(&route.paths[1], &payment_params_opt, &our_payment_hash, &Some(our_payment_secret), 15_000_000, cur_height, payment_id, &None, session_privs[2]).unwrap();
9133         check_added_monitors!(nodes[0], 1);
9134
9135         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9136         assert_eq!(events.len(), 1);
9137         pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9138
9139         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9140 }
9141
9142 #[test]
9143 fn test_keysend_payments_to_public_node() {
9144         let chanmon_cfgs = create_chanmon_cfgs(2);
9145         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9146         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9147         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9148
9149         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9150         let network_graph = nodes[0].network_graph.clone();
9151         let payer_pubkey = nodes[0].node.get_our_node_id();
9152         let payee_pubkey = nodes[1].node.get_our_node_id();
9153         let route_params = RouteParameters {
9154                 payment_params: PaymentParameters::for_keysend(payee_pubkey),
9155                 final_value_msat: 10000,
9156                 final_cltv_expiry_delta: 40,
9157         };
9158         let scorer = test_utils::TestScorer::with_penalty(0);
9159         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9160         let route = find_route(&payer_pubkey, &route_params, &network_graph, None, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
9161
9162         let test_preimage = PaymentPreimage([42; 32]);
9163         let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage), PaymentId(test_preimage.0)).unwrap();
9164         check_added_monitors!(nodes[0], 1);
9165         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9166         assert_eq!(events.len(), 1);
9167         let event = events.pop().unwrap();
9168         let path = vec![&nodes[1]];
9169         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9170         claim_payment(&nodes[0], &path, test_preimage);
9171 }
9172
9173 #[test]
9174 fn test_keysend_payments_to_private_node() {
9175         let chanmon_cfgs = create_chanmon_cfgs(2);
9176         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9177         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9178         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9179
9180         let payer_pubkey = nodes[0].node.get_our_node_id();
9181         let payee_pubkey = nodes[1].node.get_our_node_id();
9182         nodes[0].node.peer_connected(&payee_pubkey, &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
9183         nodes[1].node.peer_connected(&payer_pubkey, &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
9184
9185         let _chan = create_chan_between_nodes(&nodes[0], &nodes[1], channelmanager::provided_init_features(), channelmanager::provided_init_features());
9186         let route_params = RouteParameters {
9187                 payment_params: PaymentParameters::for_keysend(payee_pubkey),
9188                 final_value_msat: 10000,
9189                 final_cltv_expiry_delta: 40,
9190         };
9191         let network_graph = nodes[0].network_graph.clone();
9192         let first_hops = nodes[0].node.list_usable_channels();
9193         let scorer = test_utils::TestScorer::with_penalty(0);
9194         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9195         let route = find_route(
9196                 &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
9197                 nodes[0].logger, &scorer, &random_seed_bytes
9198         ).unwrap();
9199
9200         let test_preimage = PaymentPreimage([42; 32]);
9201         let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage), PaymentId(test_preimage.0)).unwrap();
9202         check_added_monitors!(nodes[0], 1);
9203         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9204         assert_eq!(events.len(), 1);
9205         let event = events.pop().unwrap();
9206         let path = vec![&nodes[1]];
9207         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9208         claim_payment(&nodes[0], &path, test_preimage);
9209 }
9210
9211 #[test]
9212 fn test_double_partial_claim() {
9213         // Test what happens if a node receives a payment, generates a PaymentClaimable event, the HTLCs
9214         // time out, the sender resends only some of the MPP parts, then the user processes the
9215         // PaymentClaimable event, ensuring they don't inadvertently claim only part of the full payment
9216         // amount.
9217         let chanmon_cfgs = create_chanmon_cfgs(4);
9218         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9219         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9220         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9221
9222         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9223         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9224         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9225         create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9226
9227         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
9228         assert_eq!(route.paths.len(), 2);
9229         route.paths.sort_by(|path_a, _| {
9230                 // Sort the path so that the path through nodes[1] comes first
9231                 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
9232                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9233         });
9234
9235         send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 15_000_000, payment_hash, payment_secret);
9236         // nodes[3] has now received a PaymentClaimable event...which it will take some (exorbitant)
9237         // amount of time to respond to.
9238
9239         // Connect some blocks to time out the payment
9240         connect_blocks(&nodes[3], TEST_FINAL_CLTV);
9241         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // To get the same height for sending later
9242
9243         let failed_destinations = vec![
9244                 HTLCDestination::FailedPayment { payment_hash },
9245                 HTLCDestination::FailedPayment { payment_hash },
9246         ];
9247         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations);
9248
9249         pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash);
9250
9251         // nodes[1] now retries one of the two paths...
9252         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
9253         check_added_monitors!(nodes[0], 2);
9254
9255         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9256         assert_eq!(events.len(), 2);
9257         pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
9258
9259         // At this point nodes[3] has received one half of the payment, and the user goes to handle
9260         // that PaymentClaimable event they got hours ago and never handled...we should refuse to claim.
9261         nodes[3].node.claim_funds(payment_preimage);
9262         check_added_monitors!(nodes[3], 0);
9263         assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
9264 }
9265
9266 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
9267 #[derive(Clone, Copy, PartialEq)]
9268 enum ExposureEvent {
9269         /// Breach occurs at HTLC forwarding (see `send_htlc`)
9270         AtHTLCForward,
9271         /// Breach occurs at HTLC reception (see `update_add_htlc`)
9272         AtHTLCReception,
9273         /// Breach occurs at outbound update_fee (see `send_update_fee`)
9274         AtUpdateFeeOutbound,
9275 }
9276
9277 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool) {
9278         // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
9279         // policy.
9280         //
9281         // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
9282         // trimmed-to-dust HTLC outbound balance and this new payment as included on next
9283         // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
9284         // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
9285         // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
9286         // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
9287         // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
9288         // might be available again for HTLC processing once the dust bandwidth has cleared up.
9289
9290         let chanmon_cfgs = create_chanmon_cfgs(2);
9291         let mut config = test_default_channel_config();
9292         config.channel_config.max_dust_htlc_exposure_msat = 5_000_000; // default setting value
9293         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9294         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
9295         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9296
9297         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
9298         let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9299         open_channel.max_htlc_value_in_flight_msat = 50_000_000;
9300         open_channel.max_accepted_htlcs = 60;
9301         if on_holder_tx {
9302                 open_channel.dust_limit_satoshis = 546;
9303         }
9304         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_channel);
9305         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9306         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_channel);
9307
9308         let opt_anchors = false;
9309
9310         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
9311
9312         if on_holder_tx {
9313                 let mut node_0_per_peer_lock;
9314                 let mut node_0_peer_state_lock;
9315                 let mut chan = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, temporary_channel_id);
9316                 chan.holder_dust_limit_satoshis = 546;
9317         }
9318
9319         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9320         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()));
9321         check_added_monitors!(nodes[1], 1);
9322
9323         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()));
9324         check_added_monitors!(nodes[0], 1);
9325
9326         let (channel_ready, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9327         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9328         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9329
9330         let dust_buffer_feerate = {
9331                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
9332                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
9333                 let chan = chan_lock.channel_by_id.get(&channel_id).unwrap();
9334                 chan.get_dust_buffer_feerate(None) as u64
9335         };
9336         let dust_outbound_htlc_on_holder_tx_msat: u64 = (dust_buffer_feerate * htlc_timeout_tx_weight(opt_anchors) / 1000 + open_channel.dust_limit_satoshis - 1) * 1000;
9337         let dust_outbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
9338
9339         let dust_inbound_htlc_on_holder_tx_msat: u64 = (dust_buffer_feerate * htlc_success_tx_weight(opt_anchors) / 1000 + open_channel.dust_limit_satoshis - 1) * 1000;
9340         let dust_inbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
9341
9342         let dust_htlc_on_counterparty_tx: u64 = 25;
9343         let dust_htlc_on_counterparty_tx_msat: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
9344
9345         if on_holder_tx {
9346                 if dust_outbound_balance {
9347                         // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9348                         // Outbound dust balance: 4372 sats
9349                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
9350                         for i in 0..dust_outbound_htlc_on_holder_tx {
9351                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
9352                                 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)) { panic!("Unexpected event at dust HTLC {}", i); }
9353                         }
9354                 } else {
9355                         // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9356                         // Inbound dust balance: 4372 sats
9357                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
9358                         for _ in 0..dust_inbound_htlc_on_holder_tx {
9359                                 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
9360                         }
9361                 }
9362         } else {
9363                 if dust_outbound_balance {
9364                         // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9365                         // Outbound dust balance: 5000 sats
9366                         for i in 0..dust_htlc_on_counterparty_tx {
9367                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
9368                                 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)) { panic!("Unexpected event at dust HTLC {}", i); }
9369                         }
9370                 } else {
9371                         // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9372                         // Inbound dust balance: 5000 sats
9373                         for _ in 0..dust_htlc_on_counterparty_tx {
9374                                 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
9375                         }
9376                 }
9377         }
9378
9379         let dust_overflow = dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx + 1);
9380         if exposure_breach_event == ExposureEvent::AtHTLCForward {
9381                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if on_holder_tx { dust_outbound_htlc_on_holder_tx_msat } else { dust_htlc_on_counterparty_tx_msat });
9382                 let mut config = UserConfig::default();
9383                 // With default dust exposure: 5000 sats
9384                 if on_holder_tx {
9385                         let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * (dust_outbound_htlc_on_holder_tx + 1);
9386                         let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * dust_inbound_htlc_on_holder_tx + dust_outbound_htlc_on_holder_tx_msat;
9387                         unwrap_send_err!(nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)), true, APIError::ChannelUnavailable { ref err }, assert_eq!(err, &format!("Cannot send value that would put our exposure to dust HTLCs at {} over the limit {} on holder commitment tx", if dust_outbound_balance { dust_outbound_overflow } else { dust_inbound_overflow }, config.channel_config.max_dust_htlc_exposure_msat)));
9388                 } else {
9389                         unwrap_send_err!(nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)), true, APIError::ChannelUnavailable { ref err }, assert_eq!(err, &format!("Cannot send value that would put our exposure to dust HTLCs at {} over the limit {} on counterparty commitment tx", dust_overflow, config.channel_config.max_dust_htlc_exposure_msat)));
9390                 }
9391         } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
9392                 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 });
9393                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
9394                 check_added_monitors!(nodes[1], 1);
9395                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9396                 assert_eq!(events.len(), 1);
9397                 let payment_event = SendEvent::from_event(events.remove(0));
9398                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9399                 // With default dust exposure: 5000 sats
9400                 if on_holder_tx {
9401                         // Outbound dust balance: 6399 sats
9402                         let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
9403                         let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
9404                         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot accept value that would put our exposure to dust HTLCs at {} over the limit {} on holder commitment tx", if dust_outbound_balance { dust_outbound_overflow } else { dust_inbound_overflow }, config.channel_config.max_dust_htlc_exposure_msat), 1);
9405                 } else {
9406                         // Outbound dust balance: 5200 sats
9407                         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot accept value that would put our exposure to dust HTLCs at {} over the limit {} on counterparty commitment tx", dust_overflow, config.channel_config.max_dust_htlc_exposure_msat), 1);
9408                 }
9409         } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
9410                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 2_500_000);
9411                 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)) { panic!("Unexpected event at update_fee-swallowed HTLC", ); }
9412                 {
9413                         let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9414                         *feerate_lock = *feerate_lock * 10;
9415                 }
9416                 nodes[0].node.timer_tick_occurred();
9417                 check_added_monitors!(nodes[0], 1);
9418                 nodes[0].logger.assert_log_contains("lightning::ln::channel".to_string(), "Cannot afford to send new feerate at 2530 without infringing max dust htlc exposure".to_string(), 1);
9419         }
9420
9421         let _ = nodes[0].node.get_and_clear_pending_msg_events();
9422         let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9423         added_monitors.clear();
9424 }
9425
9426 #[test]
9427 fn test_max_dust_htlc_exposure() {
9428         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true);
9429         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true);
9430         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true);
9431         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false);
9432         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false);
9433         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false);
9434         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true);
9435         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false);
9436         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true);
9437         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false);
9438         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false);
9439         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true);
9440 }
9441
9442 #[test]
9443 fn test_non_final_funding_tx() {
9444         let chanmon_cfgs = create_chanmon_cfgs(2);
9445         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9446         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9447         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9448
9449         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
9450         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9451         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_channel_message);
9452         let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9453         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_channel_message);
9454
9455         let best_height = nodes[0].node.best_block.read().unwrap().height();
9456
9457         let chan_id = *nodes[0].network_chan_count.borrow();
9458         let events = nodes[0].node.get_and_clear_pending_events();
9459         let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::Script::new(), sequence: Sequence(1), witness: Witness::from_vec(vec!(vec!(1))) };
9460         assert_eq!(events.len(), 1);
9461         let mut tx = match events[0] {
9462                 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
9463                         // Timelock the transaction _beyond_ the best client height + 2.
9464                         Transaction { version: chan_id as i32, lock_time: PackedLockTime(best_height + 3), input: vec![input], output: vec![TxOut {
9465                                 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
9466                         }]}
9467                 },
9468                 _ => panic!("Unexpected event"),
9469         };
9470         // Transaction should fail as it's evaluated as non-final for propagation.
9471         match nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()) {
9472                 Err(APIError::APIMisuseError { err }) => {
9473                         assert_eq!(format!("Funding transaction absolute timelock is non-final"), err);
9474                 },
9475                 _ => panic!()
9476         }
9477
9478         // However, transaction should be accepted if it's in a +2 headroom from best block.
9479         tx.lock_time = PackedLockTime(tx.lock_time.0 - 1);
9480         assert!(nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
9481         get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9482 }
9483
9484 #[test]
9485 fn accept_busted_but_better_fee() {
9486         // If a peer sends us a fee update that is too low, but higher than our previous channel
9487         // feerate, we should accept it. In the future we may want to consider closing the channel
9488         // later, but for now we only accept the update.
9489         let mut chanmon_cfgs = create_chanmon_cfgs(2);
9490         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9491         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9492         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9493
9494         create_chan_between_nodes(&nodes[0], &nodes[1], channelmanager::provided_init_features(), channelmanager::provided_init_features());
9495
9496         // Set nodes[1] to expect 5,000 sat/kW.
9497         {
9498                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
9499                 *feerate_lock = 5000;
9500         }
9501
9502         // If nodes[0] increases their feerate, even if its not enough, nodes[1] should accept it.
9503         {
9504                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9505                 *feerate_lock = 1000;
9506         }
9507         nodes[0].node.timer_tick_occurred();
9508         check_added_monitors!(nodes[0], 1);
9509
9510         let events = nodes[0].node.get_and_clear_pending_msg_events();
9511         assert_eq!(events.len(), 1);
9512         match events[0] {
9513                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9514                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9515                         commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9516                 },
9517                 _ => panic!("Unexpected event"),
9518         };
9519
9520         // If nodes[0] increases their feerate further, even if its not enough, nodes[1] should accept
9521         // it.
9522         {
9523                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9524                 *feerate_lock = 2000;
9525         }
9526         nodes[0].node.timer_tick_occurred();
9527         check_added_monitors!(nodes[0], 1);
9528
9529         let events = nodes[0].node.get_and_clear_pending_msg_events();
9530         assert_eq!(events.len(), 1);
9531         match events[0] {
9532                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9533                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9534                         commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9535                 },
9536                 _ => panic!("Unexpected event"),
9537         };
9538
9539         // However, if nodes[0] decreases their feerate, nodes[1] should reject it and close the
9540         // channel.
9541         {
9542                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9543                 *feerate_lock = 1000;
9544         }
9545         nodes[0].node.timer_tick_occurred();
9546         check_added_monitors!(nodes[0], 1);
9547
9548         let events = nodes[0].node.get_and_clear_pending_msg_events();
9549         assert_eq!(events.len(), 1);
9550         match events[0] {
9551                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
9552                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9553                         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError {
9554                                 err: "Peer's feerate much too low. Actual: 1000. Our expected lower limit: 5000 (- 250)".to_owned() });
9555                         check_closed_broadcast!(nodes[1], true);
9556                         check_added_monitors!(nodes[1], 1);
9557                 },
9558                 _ => panic!("Unexpected event"),
9559         };
9560 }