Replace manual node reloading with a macro/function in tests
[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::{ChannelMonitor, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY};
19 use crate::chain::transaction::OutPoint;
20 use crate::chain::keysinterface::{BaseSign, 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, ChannelManager, ChannelManagerReadArgs, 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::{byte_utils, 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::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 mut lock;
179                 let mut chan = get_channel_ref!(if send_from_initiator { &nodes[1] } else { &nodes[0] }, lock, temp_channel_id);
180                 chan.holder_selected_channel_reserve_satoshis = 0;
181                 chan.holder_max_htlc_value_in_flight_msat = 100_000_000;
182         }
183
184         let funding_tx = sign_funding_transaction(&nodes[0], &nodes[1], 100_000, temp_channel_id);
185         let funding_msgs = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &funding_tx);
186         create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_msgs.0);
187
188         // nodes[0] should now be able to send the full balance to nodes[1], violating nodes[1]'s
189         // security model if it ever tries to send funds back to nodes[0] (but that's not our problem).
190         if send_from_initiator {
191                 send_payment(&nodes[0], &[&nodes[1]], 100_000_000
192                         // Note that for outbound channels we have to consider the commitment tx fee and the
193                         // "fee spike buffer", which is currently a multiple of the total commitment tx fee as
194                         // well as an additional HTLC.
195                         - FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE * commit_tx_fee_msat(feerate_per_kw, 2, opt_anchors));
196         } else {
197                 send_payment(&nodes[1], &[&nodes[0]], push_amt);
198         }
199 }
200
201 #[test]
202 fn test_counterparty_no_reserve() {
203         do_test_counterparty_no_reserve(true);
204         do_test_counterparty_no_reserve(false);
205 }
206
207 #[test]
208 fn test_async_inbound_update_fee() {
209         let chanmon_cfgs = create_chanmon_cfgs(2);
210         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
211         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
212         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
213         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
214
215         // balancing
216         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
217
218         // A                                        B
219         // update_fee                            ->
220         // send (1) commitment_signed            -.
221         //                                       <- update_add_htlc/commitment_signed
222         // send (2) RAA (awaiting remote revoke) -.
223         // (1) commitment_signed is delivered    ->
224         //                                       .- send (3) RAA (awaiting remote revoke)
225         // (2) RAA is delivered                  ->
226         //                                       .- send (4) commitment_signed
227         //                                       <- (3) RAA is delivered
228         // send (5) commitment_signed            -.
229         //                                       <- (4) commitment_signed is delivered
230         // send (6) RAA                          -.
231         // (5) commitment_signed is delivered    ->
232         //                                       <- RAA
233         // (6) RAA is delivered                  ->
234
235         // First nodes[0] generates an update_fee
236         {
237                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
238                 *feerate_lock += 20;
239         }
240         nodes[0].node.timer_tick_occurred();
241         check_added_monitors!(nodes[0], 1);
242
243         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
244         assert_eq!(events_0.len(), 1);
245         let (update_msg, commitment_signed) = match events_0[0] { // (1)
246                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
247                         (update_fee.as_ref(), commitment_signed)
248                 },
249                 _ => panic!("Unexpected event"),
250         };
251
252         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
253
254         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
255         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
256         nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
257         check_added_monitors!(nodes[1], 1);
258
259         let payment_event = {
260                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
261                 assert_eq!(events_1.len(), 1);
262                 SendEvent::from_event(events_1.remove(0))
263         };
264         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
265         assert_eq!(payment_event.msgs.len(), 1);
266
267         // ...now when the messages get delivered everyone should be happy
268         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
269         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
270         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
271         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
272         check_added_monitors!(nodes[0], 1);
273
274         // deliver(1), generate (3):
275         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
276         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
277         // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
278         check_added_monitors!(nodes[1], 1);
279
280         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
281         let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
282         assert!(bs_update.update_add_htlcs.is_empty()); // (4)
283         assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
284         assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
285         assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
286         assert!(bs_update.update_fee.is_none()); // (4)
287         check_added_monitors!(nodes[1], 1);
288
289         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
290         let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
291         assert!(as_update.update_add_htlcs.is_empty()); // (5)
292         assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
293         assert!(as_update.update_fail_htlcs.is_empty()); // (5)
294         assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
295         assert!(as_update.update_fee.is_none()); // (5)
296         check_added_monitors!(nodes[0], 1);
297
298         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
299         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
300         // only (6) so get_event_msg's assert(len == 1) passes
301         check_added_monitors!(nodes[0], 1);
302
303         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
304         let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
305         check_added_monitors!(nodes[1], 1);
306
307         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
308         check_added_monitors!(nodes[0], 1);
309
310         let events_2 = nodes[0].node.get_and_clear_pending_events();
311         assert_eq!(events_2.len(), 1);
312         match events_2[0] {
313                 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
314                 _ => panic!("Unexpected event"),
315         }
316
317         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
318         check_added_monitors!(nodes[1], 1);
319 }
320
321 #[test]
322 fn test_update_fee_unordered_raa() {
323         // Just the intro to the previous test followed by an out-of-order RAA (which caused a
324         // crash in an earlier version of the update_fee patch)
325         let chanmon_cfgs = create_chanmon_cfgs(2);
326         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
327         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
328         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
329         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
330
331         // balancing
332         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
333
334         // First nodes[0] generates an update_fee
335         {
336                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
337                 *feerate_lock += 20;
338         }
339         nodes[0].node.timer_tick_occurred();
340         check_added_monitors!(nodes[0], 1);
341
342         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
343         assert_eq!(events_0.len(), 1);
344         let update_msg = match events_0[0] { // (1)
345                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
346                         update_fee.as_ref()
347                 },
348                 _ => panic!("Unexpected event"),
349         };
350
351         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
352
353         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
354         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
355         nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
356         check_added_monitors!(nodes[1], 1);
357
358         let payment_event = {
359                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
360                 assert_eq!(events_1.len(), 1);
361                 SendEvent::from_event(events_1.remove(0))
362         };
363         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
364         assert_eq!(payment_event.msgs.len(), 1);
365
366         // ...now when the messages get delivered everyone should be happy
367         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
368         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
369         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
370         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
371         check_added_monitors!(nodes[0], 1);
372
373         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
374         check_added_monitors!(nodes[1], 1);
375
376         // We can't continue, sadly, because our (1) now has a bogus signature
377 }
378
379 #[test]
380 fn test_multi_flight_update_fee() {
381         let chanmon_cfgs = create_chanmon_cfgs(2);
382         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
383         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
384         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
385         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
386
387         // A                                        B
388         // update_fee/commitment_signed          ->
389         //                                       .- send (1) RAA and (2) commitment_signed
390         // update_fee (never committed)          ->
391         // (3) update_fee                        ->
392         // We have to manually generate the above update_fee, it is allowed by the protocol but we
393         // don't track which updates correspond to which revoke_and_ack responses so we're in
394         // AwaitingRAA mode and will not generate the update_fee yet.
395         //                                       <- (1) RAA delivered
396         // (3) is generated and send (4) CS      -.
397         // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
398         // know the per_commitment_point to use for it.
399         //                                       <- (2) commitment_signed delivered
400         // revoke_and_ack                        ->
401         //                                          B should send no response here
402         // (4) commitment_signed delivered       ->
403         //                                       <- RAA/commitment_signed delivered
404         // revoke_and_ack                        ->
405
406         // First nodes[0] generates an update_fee
407         let initial_feerate;
408         {
409                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
410                 initial_feerate = *feerate_lock;
411                 *feerate_lock = initial_feerate + 20;
412         }
413         nodes[0].node.timer_tick_occurred();
414         check_added_monitors!(nodes[0], 1);
415
416         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
417         assert_eq!(events_0.len(), 1);
418         let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
419                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
420                         (update_fee.as_ref().unwrap(), commitment_signed)
421                 },
422                 _ => panic!("Unexpected event"),
423         };
424
425         // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
426         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
427         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
428         let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
429         check_added_monitors!(nodes[1], 1);
430
431         // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
432         // transaction:
433         {
434                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
435                 *feerate_lock = initial_feerate + 40;
436         }
437         nodes[0].node.timer_tick_occurred();
438         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
439         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
440
441         // Create the (3) update_fee message that nodes[0] will generate before it does...
442         let mut update_msg_2 = msgs::UpdateFee {
443                 channel_id: update_msg_1.channel_id.clone(),
444                 feerate_per_kw: (initial_feerate + 30) as u32,
445         };
446
447         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
448
449         update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
450         // Deliver (3)
451         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
452
453         // Deliver (1), generating (3) and (4)
454         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
455         let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
456         check_added_monitors!(nodes[0], 1);
457         assert!(as_second_update.update_add_htlcs.is_empty());
458         assert!(as_second_update.update_fulfill_htlcs.is_empty());
459         assert!(as_second_update.update_fail_htlcs.is_empty());
460         assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
461         // Check that the update_fee newly generated matches what we delivered:
462         assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
463         assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
464
465         // Deliver (2) commitment_signed
466         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
467         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
468         check_added_monitors!(nodes[0], 1);
469         // No commitment_signed so get_event_msg's assert(len == 1) passes
470
471         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
472         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
473         check_added_monitors!(nodes[1], 1);
474
475         // Delever (4)
476         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
477         let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
478         check_added_monitors!(nodes[1], 1);
479
480         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
481         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
482         check_added_monitors!(nodes[0], 1);
483
484         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
485         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
486         // No commitment_signed so get_event_msg's assert(len == 1) passes
487         check_added_monitors!(nodes[0], 1);
488
489         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
490         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
491         check_added_monitors!(nodes[1], 1);
492 }
493
494 fn do_test_sanity_on_in_flight_opens(steps: u8) {
495         // Previously, we had issues deserializing channels when we hadn't connected the first block
496         // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
497         // serialization round-trips and simply do steps towards opening a channel and then drop the
498         // Node objects.
499
500         let chanmon_cfgs = create_chanmon_cfgs(2);
501         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
502         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
503         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
504
505         if steps & 0b1000_0000 != 0{
506                 let block = Block {
507                         header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
508                         txdata: vec![],
509                 };
510                 connect_block(&nodes[0], &block);
511                 connect_block(&nodes[1], &block);
512         }
513
514         if steps & 0x0f == 0 { return; }
515         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
516         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
517
518         if steps & 0x0f == 1 { return; }
519         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_channel);
520         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
521
522         if steps & 0x0f == 2 { return; }
523         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_channel);
524
525         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
526
527         if steps & 0x0f == 3 { return; }
528         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
529         check_added_monitors!(nodes[0], 0);
530         let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
531
532         if steps & 0x0f == 4 { return; }
533         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
534         {
535                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
536                 assert_eq!(added_monitors.len(), 1);
537                 assert_eq!(added_monitors[0].0, funding_output);
538                 added_monitors.clear();
539         }
540         let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
541
542         if steps & 0x0f == 5 { return; }
543         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
544         {
545                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
546                 assert_eq!(added_monitors.len(), 1);
547                 assert_eq!(added_monitors[0].0, funding_output);
548                 added_monitors.clear();
549         }
550
551         let events_4 = nodes[0].node.get_and_clear_pending_events();
552         assert_eq!(events_4.len(), 0);
553
554         if steps & 0x0f == 6 { return; }
555         create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
556
557         if steps & 0x0f == 7 { return; }
558         confirm_transaction_at(&nodes[0], &tx, 2);
559         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
560         create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
561         expect_channel_ready_event(&nodes[0], &nodes[1].node.get_our_node_id());
562 }
563
564 #[test]
565 fn test_sanity_on_in_flight_opens() {
566         do_test_sanity_on_in_flight_opens(0);
567         do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
568         do_test_sanity_on_in_flight_opens(1);
569         do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
570         do_test_sanity_on_in_flight_opens(2);
571         do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
572         do_test_sanity_on_in_flight_opens(3);
573         do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
574         do_test_sanity_on_in_flight_opens(4);
575         do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
576         do_test_sanity_on_in_flight_opens(5);
577         do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
578         do_test_sanity_on_in_flight_opens(6);
579         do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
580         do_test_sanity_on_in_flight_opens(7);
581         do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
582         do_test_sanity_on_in_flight_opens(8);
583         do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
584 }
585
586 #[test]
587 fn test_update_fee_vanilla() {
588         let chanmon_cfgs = create_chanmon_cfgs(2);
589         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
590         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
591         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
592         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
593
594         {
595                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
596                 *feerate_lock += 25;
597         }
598         nodes[0].node.timer_tick_occurred();
599         check_added_monitors!(nodes[0], 1);
600
601         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
602         assert_eq!(events_0.len(), 1);
603         let (update_msg, commitment_signed) = match events_0[0] {
604                         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 } } => {
605                         (update_fee.as_ref(), commitment_signed)
606                 },
607                 _ => panic!("Unexpected event"),
608         };
609         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
610
611         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
612         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
613         check_added_monitors!(nodes[1], 1);
614
615         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
616         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
617         check_added_monitors!(nodes[0], 1);
618
619         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
620         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
621         // No commitment_signed so get_event_msg's assert(len == 1) passes
622         check_added_monitors!(nodes[0], 1);
623
624         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
625         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
626         check_added_monitors!(nodes[1], 1);
627 }
628
629 #[test]
630 fn test_update_fee_that_funder_cannot_afford() {
631         let chanmon_cfgs = create_chanmon_cfgs(2);
632         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
633         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
634         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
635         let channel_value = 5000;
636         let push_sats = 700;
637         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());
638         let channel_id = chan.2;
639         let secp_ctx = Secp256k1::new();
640         let default_config = UserConfig::default();
641         let bs_channel_reserve_sats = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value, &default_config);
642
643         let opt_anchors = false;
644
645         // Calculate the maximum feerate that A can afford. Note that we don't send an update_fee
646         // CONCURRENT_INBOUND_HTLC_FEE_BUFFER HTLCs before actually running out of local balance, so we
647         // calculate two different feerates here - the expected local limit as well as the expected
648         // remote limit.
649         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;
650         let non_buffer_feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / commitment_tx_base_weight(opt_anchors)) as u32;
651         {
652                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
653                 *feerate_lock = feerate;
654         }
655         nodes[0].node.timer_tick_occurred();
656         check_added_monitors!(nodes[0], 1);
657         let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
658
659         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
660
661         commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
662
663         // Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate set above.
664         {
665                 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
666
667                 //We made sure neither party's funds are below the dust limit and there are no HTLCs here
668                 assert_eq!(commitment_tx.output.len(), 2);
669                 let total_fee: u64 = commit_tx_fee_msat(feerate, 0, opt_anchors) / 1000;
670                 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
671                 actual_fee = channel_value - actual_fee;
672                 assert_eq!(total_fee, actual_fee);
673         }
674
675         {
676                 // Increment the feerate by a small constant, accounting for rounding errors
677                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
678                 *feerate_lock += 4;
679         }
680         nodes[0].node.timer_tick_occurred();
681         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot afford to send new feerate at {}", feerate + 4), 1);
682         check_added_monitors!(nodes[0], 0);
683
684         const INITIAL_COMMITMENT_NUMBER: u64 = 281474976710654;
685
686         // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
687         // needed to sign the new commitment tx and (2) sign the new commitment tx.
688         let (local_revocation_basepoint, local_htlc_basepoint, local_funding) = {
689                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
690                 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
691                 let chan_signer = local_chan.get_signer();
692                 let pubkeys = chan_signer.pubkeys();
693                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
694                  pubkeys.funding_pubkey)
695         };
696         let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point, remote_funding) = {
697                 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
698                 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
699                 let chan_signer = remote_chan.get_signer();
700                 let pubkeys = chan_signer.pubkeys();
701                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
702                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
703                  pubkeys.funding_pubkey)
704         };
705
706         // Assemble the set of keys we can use for signatures for our commitment_signed message.
707         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
708                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
709
710         let res = {
711                 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
712                 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
713                 let local_chan_signer = local_chan.get_signer();
714                 let mut htlcs: Vec<(HTLCOutputInCommitment, ())> = vec![];
715                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
716                         INITIAL_COMMITMENT_NUMBER - 1,
717                         push_sats,
718                         channel_value - push_sats - commit_tx_fee_msat(non_buffer_feerate + 4, 0, opt_anchors) / 1000,
719                         opt_anchors, local_funding, remote_funding,
720                         commit_tx_keys.clone(),
721                         non_buffer_feerate + 4,
722                         &mut htlcs,
723                         &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
724                 );
725                 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
726         };
727
728         let commit_signed_msg = msgs::CommitmentSigned {
729                 channel_id: chan.2,
730                 signature: res.0,
731                 htlc_signatures: res.1
732         };
733
734         let update_fee = msgs::UpdateFee {
735                 channel_id: chan.2,
736                 feerate_per_kw: non_buffer_feerate + 4,
737         };
738
739         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_fee);
740
741         //While producing the commitment_signed response after handling a received update_fee request the
742         //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
743         //Should produce and error.
744         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
745         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
746         check_added_monitors!(nodes[1], 1);
747         check_closed_broadcast!(nodes[1], true);
748         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: String::from("Funding remote cannot afford proposed new fee") });
749 }
750
751 #[test]
752 fn test_update_fee_with_fundee_update_add_htlc() {
753         let chanmon_cfgs = create_chanmon_cfgs(2);
754         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
755         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
756         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
757         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
758
759         // balancing
760         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
761
762         {
763                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
764                 *feerate_lock += 20;
765         }
766         nodes[0].node.timer_tick_occurred();
767         check_added_monitors!(nodes[0], 1);
768
769         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
770         assert_eq!(events_0.len(), 1);
771         let (update_msg, commitment_signed) = match events_0[0] {
772                         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 } } => {
773                         (update_fee.as_ref(), commitment_signed)
774                 },
775                 _ => panic!("Unexpected event"),
776         };
777         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
778         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
779         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
780         check_added_monitors!(nodes[1], 1);
781
782         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 800000);
783
784         // nothing happens since node[1] is in AwaitingRemoteRevoke
785         nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
786         {
787                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
788                 assert_eq!(added_monitors.len(), 0);
789                 added_monitors.clear();
790         }
791         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
792         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
793         // node[1] has nothing to do
794
795         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
796         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
797         check_added_monitors!(nodes[0], 1);
798
799         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
800         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
801         // No commitment_signed so get_event_msg's assert(len == 1) passes
802         check_added_monitors!(nodes[0], 1);
803         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
804         check_added_monitors!(nodes[1], 1);
805         // AwaitingRemoteRevoke ends here
806
807         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
808         assert_eq!(commitment_update.update_add_htlcs.len(), 1);
809         assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
810         assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
811         assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
812         assert_eq!(commitment_update.update_fee.is_none(), true);
813
814         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
815         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
816         check_added_monitors!(nodes[0], 1);
817         let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
818
819         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
820         check_added_monitors!(nodes[1], 1);
821         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
822
823         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
824         check_added_monitors!(nodes[1], 1);
825         let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
826         // No commitment_signed so get_event_msg's assert(len == 1) passes
827
828         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
829         check_added_monitors!(nodes[0], 1);
830         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
831
832         expect_pending_htlcs_forwardable!(nodes[0]);
833
834         let events = nodes[0].node.get_and_clear_pending_events();
835         assert_eq!(events.len(), 1);
836         match events[0] {
837                 Event::PaymentReceived { .. } => { },
838                 _ => panic!("Unexpected event"),
839         };
840
841         claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
842
843         send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
844         send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
845         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
846         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
847         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
848 }
849
850 #[test]
851 fn test_update_fee() {
852         let chanmon_cfgs = create_chanmon_cfgs(2);
853         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
854         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
855         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
856         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
857         let channel_id = chan.2;
858
859         // A                                        B
860         // (1) update_fee/commitment_signed      ->
861         //                                       <- (2) revoke_and_ack
862         //                                       .- send (3) commitment_signed
863         // (4) update_fee/commitment_signed      ->
864         //                                       .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
865         //                                       <- (3) commitment_signed delivered
866         // send (6) revoke_and_ack               -.
867         //                                       <- (5) deliver revoke_and_ack
868         // (6) deliver revoke_and_ack            ->
869         //                                       .- send (7) commitment_signed in response to (4)
870         //                                       <- (7) deliver commitment_signed
871         // revoke_and_ack                        ->
872
873         // Create and deliver (1)...
874         let feerate;
875         {
876                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
877                 feerate = *feerate_lock;
878                 *feerate_lock = feerate + 20;
879         }
880         nodes[0].node.timer_tick_occurred();
881         check_added_monitors!(nodes[0], 1);
882
883         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
884         assert_eq!(events_0.len(), 1);
885         let (update_msg, commitment_signed) = match events_0[0] {
886                         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 } } => {
887                         (update_fee.as_ref(), commitment_signed)
888                 },
889                 _ => panic!("Unexpected event"),
890         };
891         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
892
893         // Generate (2) and (3):
894         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
895         let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
896         check_added_monitors!(nodes[1], 1);
897
898         // Deliver (2):
899         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
900         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
901         check_added_monitors!(nodes[0], 1);
902
903         // Create and deliver (4)...
904         {
905                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
906                 *feerate_lock = feerate + 30;
907         }
908         nodes[0].node.timer_tick_occurred();
909         check_added_monitors!(nodes[0], 1);
910         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
911         assert_eq!(events_0.len(), 1);
912         let (update_msg, commitment_signed) = match events_0[0] {
913                         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 } } => {
914                         (update_fee.as_ref(), commitment_signed)
915                 },
916                 _ => panic!("Unexpected event"),
917         };
918
919         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
920         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
921         check_added_monitors!(nodes[1], 1);
922         // ... creating (5)
923         let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
924         // No commitment_signed so get_event_msg's assert(len == 1) passes
925
926         // Handle (3), creating (6):
927         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
928         check_added_monitors!(nodes[0], 1);
929         let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
930         // No commitment_signed so get_event_msg's assert(len == 1) passes
931
932         // Deliver (5):
933         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
934         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
935         check_added_monitors!(nodes[0], 1);
936
937         // Deliver (6), creating (7):
938         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
939         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
940         assert!(commitment_update.update_add_htlcs.is_empty());
941         assert!(commitment_update.update_fulfill_htlcs.is_empty());
942         assert!(commitment_update.update_fail_htlcs.is_empty());
943         assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
944         assert!(commitment_update.update_fee.is_none());
945         check_added_monitors!(nodes[1], 1);
946
947         // Deliver (7)
948         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
949         check_added_monitors!(nodes[0], 1);
950         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
951         // No commitment_signed so get_event_msg's assert(len == 1) passes
952
953         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
954         check_added_monitors!(nodes[1], 1);
955         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
956
957         assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
958         assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
959         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
960         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
961         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
962 }
963
964 #[test]
965 fn fake_network_test() {
966         // Simple test which builds a network of ChannelManagers, connects them to each other, and
967         // tests that payments get routed and transactions broadcast in semi-reasonable ways.
968         let chanmon_cfgs = create_chanmon_cfgs(4);
969         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
970         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
971         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
972
973         // Create some initial channels
974         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
975         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
976         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
977
978         // Rebalance the network a bit by relaying one payment through all the channels...
979         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
980         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
981         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
982         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
983
984         // Send some more payments
985         send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
986         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
987         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
988
989         // Test failure packets
990         let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
991         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
992
993         // Add a new channel that skips 3
994         let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
995
996         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
997         send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
998         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
999         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1000         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1001         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1002         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1003
1004         // Do some rebalance loop payments, simultaneously
1005         let mut hops = Vec::with_capacity(3);
1006         hops.push(RouteHop {
1007                 pubkey: nodes[2].node.get_our_node_id(),
1008                 node_features: NodeFeatures::empty(),
1009                 short_channel_id: chan_2.0.contents.short_channel_id,
1010                 channel_features: ChannelFeatures::empty(),
1011                 fee_msat: 0,
1012                 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1013         });
1014         hops.push(RouteHop {
1015                 pubkey: nodes[3].node.get_our_node_id(),
1016                 node_features: NodeFeatures::empty(),
1017                 short_channel_id: chan_3.0.contents.short_channel_id,
1018                 channel_features: ChannelFeatures::empty(),
1019                 fee_msat: 0,
1020                 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1021         });
1022         hops.push(RouteHop {
1023                 pubkey: nodes[1].node.get_our_node_id(),
1024                 node_features: channelmanager::provided_node_features(),
1025                 short_channel_id: chan_4.0.contents.short_channel_id,
1026                 channel_features: channelmanager::provided_channel_features(),
1027                 fee_msat: 1000000,
1028                 cltv_expiry_delta: TEST_FINAL_CLTV,
1029         });
1030         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;
1031         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;
1032         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;
1033
1034         let mut hops = Vec::with_capacity(3);
1035         hops.push(RouteHop {
1036                 pubkey: nodes[3].node.get_our_node_id(),
1037                 node_features: NodeFeatures::empty(),
1038                 short_channel_id: chan_4.0.contents.short_channel_id,
1039                 channel_features: ChannelFeatures::empty(),
1040                 fee_msat: 0,
1041                 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1042         });
1043         hops.push(RouteHop {
1044                 pubkey: nodes[2].node.get_our_node_id(),
1045                 node_features: NodeFeatures::empty(),
1046                 short_channel_id: chan_3.0.contents.short_channel_id,
1047                 channel_features: ChannelFeatures::empty(),
1048                 fee_msat: 0,
1049                 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1050         });
1051         hops.push(RouteHop {
1052                 pubkey: nodes[1].node.get_our_node_id(),
1053                 node_features: channelmanager::provided_node_features(),
1054                 short_channel_id: chan_2.0.contents.short_channel_id,
1055                 channel_features: channelmanager::provided_channel_features(),
1056                 fee_msat: 1000000,
1057                 cltv_expiry_delta: TEST_FINAL_CLTV,
1058         });
1059         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;
1060         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;
1061         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;
1062
1063         // Claim the rebalances...
1064         fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1065         claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1066
1067         // Close down the channels...
1068         close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1069         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
1070         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1071         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1072         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1073         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1074         close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1075         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1076         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1077         close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1078         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1079         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1080 }
1081
1082 #[test]
1083 fn holding_cell_htlc_counting() {
1084         // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1085         // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1086         // commitment dance rounds.
1087         let chanmon_cfgs = create_chanmon_cfgs(3);
1088         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1089         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1090         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1091         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1092         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1093
1094         let mut payments = Vec::new();
1095         for _ in 0..crate::ln::channel::OUR_MAX_HTLCS {
1096                 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1097                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
1098                 payments.push((payment_preimage, payment_hash));
1099         }
1100         check_added_monitors!(nodes[1], 1);
1101
1102         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1103         assert_eq!(events.len(), 1);
1104         let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1105         assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1106
1107         // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1108         // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1109         // another HTLC.
1110         let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1111         {
1112                 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 },
1113                         assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1114                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1115                 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1116         }
1117
1118         // This should also be true if we try to forward a payment.
1119         let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1120         {
1121                 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
1122                 check_added_monitors!(nodes[0], 1);
1123         }
1124
1125         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1126         assert_eq!(events.len(), 1);
1127         let payment_event = SendEvent::from_event(events.pop().unwrap());
1128         assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1129
1130         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1131         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1132         // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1133         // fails), the second will process the resulting failure and fail the HTLC backward.
1134         expect_pending_htlcs_forwardable!(nodes[1]);
1135         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 }]);
1136         check_added_monitors!(nodes[1], 1);
1137
1138         let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1139         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1140         commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1141
1142         expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1143
1144         // Now forward all the pending HTLCs and claim them back
1145         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1146         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1147         check_added_monitors!(nodes[2], 1);
1148
1149         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1150         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1151         check_added_monitors!(nodes[1], 1);
1152         let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1153
1154         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1155         check_added_monitors!(nodes[1], 1);
1156         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1157
1158         for ref update in as_updates.update_add_htlcs.iter() {
1159                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1160         }
1161         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1162         check_added_monitors!(nodes[2], 1);
1163         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1164         check_added_monitors!(nodes[2], 1);
1165         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1166
1167         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1168         check_added_monitors!(nodes[1], 1);
1169         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1170         check_added_monitors!(nodes[1], 1);
1171         let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1172
1173         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1174         check_added_monitors!(nodes[2], 1);
1175
1176         expect_pending_htlcs_forwardable!(nodes[2]);
1177
1178         let events = nodes[2].node.get_and_clear_pending_events();
1179         assert_eq!(events.len(), payments.len());
1180         for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1181                 match event {
1182                         &Event::PaymentReceived { ref payment_hash, .. } => {
1183                                 assert_eq!(*payment_hash, *hash);
1184                         },
1185                         _ => panic!("Unexpected event"),
1186                 };
1187         }
1188
1189         for (preimage, _) in payments.drain(..) {
1190                 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1191         }
1192
1193         send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1194 }
1195
1196 #[test]
1197 fn duplicate_htlc_test() {
1198         // Test that we accept duplicate payment_hash HTLCs across the network and that
1199         // claiming/failing them are all separate and don't affect each other
1200         let chanmon_cfgs = create_chanmon_cfgs(6);
1201         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1202         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1203         let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1204
1205         // Create some initial channels to route via 3 to 4/5 from 0/1/2
1206         create_announced_chan_between_nodes(&nodes, 0, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1207         create_announced_chan_between_nodes(&nodes, 1, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1208         create_announced_chan_between_nodes(&nodes, 2, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1209         create_announced_chan_between_nodes(&nodes, 3, 4, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1210         create_announced_chan_between_nodes(&nodes, 3, 5, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1211
1212         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1213
1214         *nodes[0].network_payment_count.borrow_mut() -= 1;
1215         assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1216
1217         *nodes[0].network_payment_count.borrow_mut() -= 1;
1218         assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1219
1220         claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1221         fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1222         claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1223 }
1224
1225 #[test]
1226 fn test_duplicate_htlc_different_direction_onchain() {
1227         // Test that ChannelMonitor doesn't generate 2 preimage txn
1228         // when we have 2 HTLCs with same preimage that go across a node
1229         // in opposite directions, even with the same payment secret.
1230         let chanmon_cfgs = create_chanmon_cfgs(2);
1231         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1232         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1233         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1234
1235         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1236
1237         // balancing
1238         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1239
1240         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1241
1242         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1243         let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200).unwrap();
1244         send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1245
1246         // Provide preimage to node 0 by claiming payment
1247         nodes[0].node.claim_funds(payment_preimage);
1248         expect_payment_claimed!(nodes[0], payment_hash, 800_000);
1249         check_added_monitors!(nodes[0], 1);
1250
1251         // Broadcast node 1 commitment txn
1252         let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1253
1254         assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1255         let mut has_both_htlcs = 0; // check htlcs match ones committed
1256         for outp in remote_txn[0].output.iter() {
1257                 if outp.value == 800_000 / 1000 {
1258                         has_both_htlcs += 1;
1259                 } else if outp.value == 900_000 / 1000 {
1260                         has_both_htlcs += 1;
1261                 }
1262         }
1263         assert_eq!(has_both_htlcs, 2);
1264
1265         mine_transaction(&nodes[0], &remote_txn[0]);
1266         check_added_monitors!(nodes[0], 1);
1267         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
1268         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
1269
1270         let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1271         assert_eq!(claim_txn.len(), 5);
1272
1273         check_spends!(claim_txn[0], remote_txn[0]); // Immediate HTLC claim with preimage
1274         check_spends!(claim_txn[1], chan_1.3); // Alternative commitment tx
1275         check_spends!(claim_txn[2], claim_txn[1]); // HTLC spend in alternative commitment tx
1276
1277         check_spends!(claim_txn[3], remote_txn[0]);
1278         check_spends!(claim_txn[4], remote_txn[0]);
1279         let preimage_tx = &claim_txn[0];
1280         let (preimage_bump_tx, timeout_tx) = if claim_txn[3].input[0].previous_output == preimage_tx.input[0].previous_output {
1281                 (&claim_txn[3], &claim_txn[4])
1282         } else {
1283                 (&claim_txn[4], &claim_txn[3])
1284         };
1285
1286         assert_eq!(preimage_tx.input.len(), 1);
1287         assert_eq!(preimage_bump_tx.input.len(), 1);
1288
1289         assert_eq!(preimage_tx.input.len(), 1);
1290         assert_eq!(preimage_tx.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1291         assert_eq!(remote_txn[0].output[preimage_tx.input[0].previous_output.vout as usize].value, 800);
1292
1293         assert_eq!(timeout_tx.input.len(), 1);
1294         assert_eq!(timeout_tx.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1295         check_spends!(timeout_tx, remote_txn[0]);
1296         assert_eq!(remote_txn[0].output[timeout_tx.input[0].previous_output.vout as usize].value, 900);
1297
1298         let events = nodes[0].node.get_and_clear_pending_msg_events();
1299         assert_eq!(events.len(), 3);
1300         for e in events {
1301                 match e {
1302                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1303                         MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1304                                 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1305                                 assert_eq!(msg.data, "Channel closed because commitment or closing transaction was confirmed on chain.");
1306                         },
1307                         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, .. } } => {
1308                                 assert!(update_add_htlcs.is_empty());
1309                                 assert!(update_fail_htlcs.is_empty());
1310                                 assert_eq!(update_fulfill_htlcs.len(), 1);
1311                                 assert!(update_fail_malformed_htlcs.is_empty());
1312                                 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1313                         },
1314                         _ => panic!("Unexpected event"),
1315                 }
1316         }
1317 }
1318
1319 #[test]
1320 fn test_basic_channel_reserve() {
1321         let chanmon_cfgs = create_chanmon_cfgs(2);
1322         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1323         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1324         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1325         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1326
1327         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1328         let channel_reserve = chan_stat.channel_reserve_msat;
1329
1330         // The 2* and +1 are for the fee spike reserve.
1331         let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], chan.2), 1 + 1, get_opt_anchors!(nodes[0], chan.2));
1332         let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1333         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send + 1);
1334         let err = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).err().unwrap();
1335         match err {
1336                 PaymentSendFailure::AllFailedRetrySafe(ref fails) => {
1337                         match &fails[0] {
1338                                 &APIError::ChannelUnavailable{ref err} =>
1339                                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1340                                 _ => panic!("Unexpected error variant"),
1341                         }
1342                 },
1343                 _ => panic!("Unexpected error variant"),
1344         }
1345         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1346         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);
1347
1348         send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1349 }
1350
1351 #[test]
1352 fn test_fee_spike_violation_fails_htlc() {
1353         let chanmon_cfgs = create_chanmon_cfgs(2);
1354         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1355         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1356         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1357         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1358
1359         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3460001);
1360         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1361         let secp_ctx = Secp256k1::new();
1362         let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1363
1364         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1365
1366         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1367         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &Some(payment_secret), cur_height, &None).unwrap();
1368         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1369         let msg = msgs::UpdateAddHTLC {
1370                 channel_id: chan.2,
1371                 htlc_id: 0,
1372                 amount_msat: htlc_msat,
1373                 payment_hash: payment_hash,
1374                 cltv_expiry: htlc_cltv,
1375                 onion_routing_packet: onion_packet,
1376         };
1377
1378         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1379
1380         // Now manually create the commitment_signed message corresponding to the update_add
1381         // nodes[0] just sent. In the code for construction of this message, "local" refers
1382         // to the sender of the message, and "remote" refers to the receiver.
1383
1384         let feerate_per_kw = get_feerate!(nodes[0], chan.2);
1385
1386         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1387
1388         // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1389         // needed to sign the new commitment tx and (2) sign the new commitment tx.
1390         let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1391                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
1392                 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
1393                 let chan_signer = local_chan.get_signer();
1394                 // Make the signer believe we validated another commitment, so we can release the secret
1395                 chan_signer.get_enforcement_state().last_holder_commitment -= 1;
1396
1397                 let pubkeys = chan_signer.pubkeys();
1398                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1399                  chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1400                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1401                  chan_signer.pubkeys().funding_pubkey)
1402         };
1403         let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1404                 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
1405                 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
1406                 let chan_signer = remote_chan.get_signer();
1407                 let pubkeys = chan_signer.pubkeys();
1408                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1409                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1410                  chan_signer.pubkeys().funding_pubkey)
1411         };
1412
1413         // Assemble the set of keys we can use for signatures for our commitment_signed message.
1414         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1415                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
1416
1417         // Build the remote commitment transaction so we can sign it, and then later use the
1418         // signature for the commitment_signed message.
1419         let local_chan_balance = 1313;
1420
1421         let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1422                 offered: false,
1423                 amount_msat: 3460001,
1424                 cltv_expiry: htlc_cltv,
1425                 payment_hash,
1426                 transaction_output_index: Some(1),
1427         };
1428
1429         let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1430
1431         let res = {
1432                 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
1433                 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
1434                 let local_chan_signer = local_chan.get_signer();
1435                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1436                         commitment_number,
1437                         95000,
1438                         local_chan_balance,
1439                         local_chan.opt_anchors(), local_funding, remote_funding,
1440                         commit_tx_keys.clone(),
1441                         feerate_per_kw,
1442                         &mut vec![(accepted_htlc_info, ())],
1443                         &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1444                 );
1445                 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
1446         };
1447
1448         let commit_signed_msg = msgs::CommitmentSigned {
1449                 channel_id: chan.2,
1450                 signature: res.0,
1451                 htlc_signatures: res.1
1452         };
1453
1454         // Send the commitment_signed message to the nodes[1].
1455         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1456         let _ = nodes[1].node.get_and_clear_pending_msg_events();
1457
1458         // Send the RAA to nodes[1].
1459         let raa_msg = msgs::RevokeAndACK {
1460                 channel_id: chan.2,
1461                 per_commitment_secret: local_secret,
1462                 next_per_commitment_point: next_local_point
1463         };
1464         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1465
1466         let events = nodes[1].node.get_and_clear_pending_msg_events();
1467         assert_eq!(events.len(), 1);
1468         // Make sure the HTLC failed in the way we expect.
1469         match events[0] {
1470                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1471                         assert_eq!(update_fail_htlcs.len(), 1);
1472                         update_fail_htlcs[0].clone()
1473                 },
1474                 _ => panic!("Unexpected event"),
1475         };
1476         nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1477                 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", ::hex::encode(raa_msg.channel_id)), 1);
1478
1479         check_added_monitors!(nodes[1], 2);
1480 }
1481
1482 #[test]
1483 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1484         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1485         // Set the fee rate for the channel very high, to the point where the fundee
1486         // sending any above-dust amount would result in a channel reserve violation.
1487         // In this test we check that we would be prevented from sending an HTLC in
1488         // this situation.
1489         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1490         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1491         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1492         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1493         let default_config = UserConfig::default();
1494         let opt_anchors = false;
1495
1496         let mut push_amt = 100_000_000;
1497         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1498
1499         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1500
1501         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1502
1503         // Sending exactly enough to hit the reserve amount should be accepted
1504         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1505                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1506         }
1507
1508         // However one more HTLC should be significantly over the reserve amount and fail.
1509         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1510         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 },
1511                 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1512         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1513         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);
1514 }
1515
1516 #[test]
1517 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1518         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1519         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1520         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1521         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1522         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1523         let default_config = UserConfig::default();
1524         let opt_anchors = false;
1525
1526         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1527         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1528         // transaction fee with 0 HTLCs (183 sats)).
1529         let mut push_amt = 100_000_000;
1530         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1531         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1532         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1533
1534         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1535         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1536                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1537         }
1538
1539         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 700_000);
1540         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1541         let secp_ctx = Secp256k1::new();
1542         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1543         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1544         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1545         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 700_000, &Some(payment_secret), cur_height, &None).unwrap();
1546         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1547         let msg = msgs::UpdateAddHTLC {
1548                 channel_id: chan.2,
1549                 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1550                 amount_msat: htlc_msat,
1551                 payment_hash: payment_hash,
1552                 cltv_expiry: htlc_cltv,
1553                 onion_routing_packet: onion_packet,
1554         };
1555
1556         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1557         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1558         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);
1559         assert_eq!(nodes[0].node.list_channels().len(), 0);
1560         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1561         assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1562         check_added_monitors!(nodes[0], 1);
1563         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() });
1564 }
1565
1566 #[test]
1567 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1568         // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1569         // calculating our commitment transaction fee (this was previously broken).
1570         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1571         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1572
1573         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1574         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1575         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1576         let default_config = UserConfig::default();
1577         let opt_anchors = false;
1578
1579         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1580         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1581         // transaction fee with 0 HTLCs (183 sats)).
1582         let mut push_amt = 100_000_000;
1583         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1584         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1585         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1586
1587         let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1588                 + feerate_per_kw as u64 * htlc_success_tx_weight(opt_anchors) / 1000 * 1000 - 1;
1589         // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1590         // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1591         // commitment transaction fee.
1592         let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1593
1594         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1595         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1596                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1597         }
1598
1599         // One more than the dust amt should fail, however.
1600         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt + 1);
1601         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 },
1602                 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1603 }
1604
1605 #[test]
1606 fn test_chan_init_feerate_unaffordability() {
1607         // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to
1608         // channel reserve and feerate requirements.
1609         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1610         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1611         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1612         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1613         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1614         let default_config = UserConfig::default();
1615         let opt_anchors = false;
1616
1617         // Set the push_msat amount such that nodes[0] will not be able to afford to add even a single
1618         // HTLC.
1619         let mut push_amt = 100_000_000;
1620         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1621         assert_eq!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt + 1, 42, None).unwrap_err(),
1622                 APIError::APIMisuseError { err: "Funding amount (356) can't even pay fee for initial commitment transaction fee of 357.".to_string() });
1623
1624         // During open, we don't have a "counterparty channel reserve" to check against, so that
1625         // requirement only comes into play on the open_channel handling side.
1626         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1627         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt, 42, None).unwrap();
1628         let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
1629         open_channel_msg.push_msat += 1;
1630         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_channel_msg);
1631
1632         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1633         assert_eq!(msg_events.len(), 1);
1634         match msg_events[0] {
1635                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1636                         assert_eq!(msg.data, "Insufficient funding amount for initial reserve");
1637                 },
1638                 _ => panic!("Unexpected event"),
1639         }
1640 }
1641
1642 #[test]
1643 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1644         // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1645         // calculating our counterparty's commitment transaction fee (this was previously broken).
1646         let chanmon_cfgs = create_chanmon_cfgs(2);
1647         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1648         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1649         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1650         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1651
1652         let payment_amt = 46000; // Dust amount
1653         // In the previous code, these first four payments would succeed.
1654         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1655         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1656         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1657         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1658
1659         // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
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         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1665
1666         // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1667         // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1668         // transaction fee and therefore perceived this next payment as a channel reserve violation.
1669         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1670 }
1671
1672 #[test]
1673 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1674         let chanmon_cfgs = create_chanmon_cfgs(3);
1675         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1676         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1677         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1678         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1679         let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1680
1681         let feemsat = 239;
1682         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1683         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1684         let feerate = get_feerate!(nodes[0], chan.2);
1685         let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
1686
1687         // Add a 2* and +1 for the fee spike reserve.
1688         let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1689         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;
1690         let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1691
1692         // Add a pending HTLC.
1693         let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1694         let payment_event_1 = {
1695                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1696                 check_added_monitors!(nodes[0], 1);
1697
1698                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1699                 assert_eq!(events.len(), 1);
1700                 SendEvent::from_event(events.remove(0))
1701         };
1702         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1703
1704         // Attempt to trigger a channel reserve violation --> payment failure.
1705         let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2, opt_anchors);
1706         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;
1707         let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1708         let (route_2, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_2);
1709
1710         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1711         let secp_ctx = Secp256k1::new();
1712         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1713         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1714         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1715         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height, &None).unwrap();
1716         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1717         let msg = msgs::UpdateAddHTLC {
1718                 channel_id: chan.2,
1719                 htlc_id: 1,
1720                 amount_msat: htlc_msat + 1,
1721                 payment_hash: our_payment_hash_1,
1722                 cltv_expiry: htlc_cltv,
1723                 onion_routing_packet: onion_packet,
1724         };
1725
1726         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1727         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1728         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1729         assert_eq!(nodes[1].node.list_channels().len(), 1);
1730         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1731         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1732         check_added_monitors!(nodes[1], 1);
1733         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() });
1734 }
1735
1736 #[test]
1737 fn test_inbound_outbound_capacity_is_not_zero() {
1738         let chanmon_cfgs = create_chanmon_cfgs(2);
1739         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1740         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1741         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1742         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1743         let channels0 = node_chanmgrs[0].list_channels();
1744         let channels1 = node_chanmgrs[1].list_channels();
1745         let default_config = UserConfig::default();
1746         assert_eq!(channels0.len(), 1);
1747         assert_eq!(channels1.len(), 1);
1748
1749         let reserve = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config);
1750         assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1751         assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1752
1753         assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1754         assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1755 }
1756
1757 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64, opt_anchors: bool) -> u64 {
1758         (commitment_tx_base_weight(opt_anchors) + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1759 }
1760
1761 #[test]
1762 fn test_channel_reserve_holding_cell_htlcs() {
1763         let chanmon_cfgs = create_chanmon_cfgs(3);
1764         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1765         // When this test was written, the default base fee floated based on the HTLC count.
1766         // It is now fixed, so we simply set the fee to the expected value here.
1767         let mut config = test_default_channel_config();
1768         config.channel_config.forwarding_fee_base_msat = 239;
1769         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1770         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1771         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1772         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1773
1774         let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1775         let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1776
1777         let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1778         let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1779
1780         macro_rules! expect_forward {
1781                 ($node: expr) => {{
1782                         let mut events = $node.node.get_and_clear_pending_msg_events();
1783                         assert_eq!(events.len(), 1);
1784                         check_added_monitors!($node, 1);
1785                         let payment_event = SendEvent::from_event(events.remove(0));
1786                         payment_event
1787                 }}
1788         }
1789
1790         let feemsat = 239; // set above
1791         let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1792         let feerate = get_feerate!(nodes[0], chan_1.2);
1793         let opt_anchors = get_opt_anchors!(nodes[0], chan_1.2);
1794
1795         let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1796
1797         // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1798         {
1799                 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id())
1800                         .with_features(channelmanager::provided_invoice_features()).with_max_channel_saturation_power_of_half(0);
1801                 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);
1802                 route.paths[0].last_mut().unwrap().fee_msat += 1;
1803                 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1804
1805                 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 },
1806                         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)));
1807                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1808                 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);
1809         }
1810
1811         // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1812         // nodes[0]'s wealth
1813         loop {
1814                 let amt_msat = recv_value_0 + total_fee_msat;
1815                 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1816                 // Also, ensure that each payment has enough to be over the dust limit to
1817                 // ensure it'll be included in each commit tx fee calculation.
1818                 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1819                 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1820                 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1821                         break;
1822                 }
1823
1824                 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id())
1825                         .with_features(channelmanager::provided_invoice_features()).with_max_channel_saturation_power_of_half(0);
1826                 let route = get_route!(nodes[0], payment_params, recv_value_0, TEST_FINAL_CLTV).unwrap();
1827                 let (payment_preimage, ..) = send_along_route(&nodes[0], route, &[&nodes[1], &nodes[2]], recv_value_0);
1828                 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1829
1830                 let (stat01_, stat11_, stat12_, stat22_) = (
1831                         get_channel_value_stat!(nodes[0], chan_1.2),
1832                         get_channel_value_stat!(nodes[1], chan_1.2),
1833                         get_channel_value_stat!(nodes[1], chan_2.2),
1834                         get_channel_value_stat!(nodes[2], chan_2.2),
1835                 );
1836
1837                 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1838                 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1839                 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1840                 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1841                 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1842         }
1843
1844         // adding pending output.
1845         // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1846         // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1847         // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1848         // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1849         // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1850         // cases where 1 msat over X amount will cause a payment failure, but anything less than
1851         // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1852         // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1853         // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1854         // policy.
1855         let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1856         let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1857         let amt_msat_1 = recv_value_1 + total_fee_msat;
1858
1859         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);
1860         let payment_event_1 = {
1861                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1862                 check_added_monitors!(nodes[0], 1);
1863
1864                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1865                 assert_eq!(events.len(), 1);
1866                 SendEvent::from_event(events.remove(0))
1867         };
1868         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1869
1870         // channel reserve test with htlc pending output > 0
1871         let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1872         {
1873                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_2 + 1);
1874                 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 },
1875                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1876                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1877         }
1878
1879         // split the rest to test holding cell
1880         let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1881         let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1882         let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1883         let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1884         {
1885                 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
1886                 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);
1887         }
1888
1889         // now see if they go through on both sides
1890         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);
1891         // but this will stuck in the holding cell
1892         nodes[0].node.send_payment(&route_21, our_payment_hash_21, &Some(our_payment_secret_21), PaymentId(our_payment_hash_21.0)).unwrap();
1893         check_added_monitors!(nodes[0], 0);
1894         let events = nodes[0].node.get_and_clear_pending_events();
1895         assert_eq!(events.len(), 0);
1896
1897         // test with outbound holding cell amount > 0
1898         {
1899                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22+1);
1900                 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 },
1901                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1902                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1903                 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);
1904         }
1905
1906         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);
1907         // this will also stuck in the holding cell
1908         nodes[0].node.send_payment(&route_22, our_payment_hash_22, &Some(our_payment_secret_22), PaymentId(our_payment_hash_22.0)).unwrap();
1909         check_added_monitors!(nodes[0], 0);
1910         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1911         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1912
1913         // flush the pending htlc
1914         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1915         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1916         check_added_monitors!(nodes[1], 1);
1917
1918         // the pending htlc should be promoted to committed
1919         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1920         check_added_monitors!(nodes[0], 1);
1921         let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1922
1923         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1924         let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1925         // No commitment_signed so get_event_msg's assert(len == 1) passes
1926         check_added_monitors!(nodes[0], 1);
1927
1928         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1929         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1930         check_added_monitors!(nodes[1], 1);
1931
1932         expect_pending_htlcs_forwardable!(nodes[1]);
1933
1934         let ref payment_event_11 = expect_forward!(nodes[1]);
1935         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1936         commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1937
1938         expect_pending_htlcs_forwardable!(nodes[2]);
1939         expect_payment_received!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
1940
1941         // flush the htlcs in the holding cell
1942         assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1943         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1944         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1945         commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1946         expect_pending_htlcs_forwardable!(nodes[1]);
1947
1948         let ref payment_event_3 = expect_forward!(nodes[1]);
1949         assert_eq!(payment_event_3.msgs.len(), 2);
1950         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1951         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1952
1953         commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1954         expect_pending_htlcs_forwardable!(nodes[2]);
1955
1956         let events = nodes[2].node.get_and_clear_pending_events();
1957         assert_eq!(events.len(), 2);
1958         match events[0] {
1959                 Event::PaymentReceived { ref payment_hash, ref purpose, amount_msat } => {
1960                         assert_eq!(our_payment_hash_21, *payment_hash);
1961                         assert_eq!(recv_value_21, amount_msat);
1962                         match &purpose {
1963                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1964                                         assert!(payment_preimage.is_none());
1965                                         assert_eq!(our_payment_secret_21, *payment_secret);
1966                                 },
1967                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
1968                         }
1969                 },
1970                 _ => panic!("Unexpected event"),
1971         }
1972         match events[1] {
1973                 Event::PaymentReceived { ref payment_hash, ref purpose, amount_msat } => {
1974                         assert_eq!(our_payment_hash_22, *payment_hash);
1975                         assert_eq!(recv_value_22, amount_msat);
1976                         match &purpose {
1977                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1978                                         assert!(payment_preimage.is_none());
1979                                         assert_eq!(our_payment_secret_22, *payment_secret);
1980                                 },
1981                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
1982                         }
1983                 },
1984                 _ => panic!("Unexpected event"),
1985         }
1986
1987         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
1988         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
1989         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
1990
1991         let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1, opt_anchors);
1992         let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
1993         send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
1994
1995         let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
1996         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);
1997         let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
1998         assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
1999         assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2000
2001         let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
2002         assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2003 }
2004
2005 #[test]
2006 fn channel_reserve_in_flight_removes() {
2007         // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2008         // can send to its counterparty, but due to update ordering, the other side may not yet have
2009         // considered those HTLCs fully removed.
2010         // This tests that we don't count HTLCs which will not be included in the next remote
2011         // commitment transaction towards the reserve value (as it implies no commitment transaction
2012         // will be generated which violates the remote reserve value).
2013         // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2014         // To test this we:
2015         //  * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2016         //    you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2017         //    you only consider the value of the first HTLC, it may not),
2018         //  * start routing a third HTLC from A to B,
2019         //  * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2020         //    the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2021         //  * deliver the first fulfill from B
2022         //  * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2023         //    claim,
2024         //  * deliver A's response CS and RAA.
2025         //    This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2026         //    removed it fully. B now has the push_msat plus the first two HTLCs in value.
2027         //  * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2028         //    of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2029         let chanmon_cfgs = create_chanmon_cfgs(2);
2030         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2031         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2032         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2033         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2034
2035         let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
2036         // Route the first two HTLCs.
2037         let payment_value_1 = b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000;
2038         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], payment_value_1);
2039         let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20_000);
2040
2041         // Start routing the third HTLC (this is just used to get everyone in the right state).
2042         let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
2043         let send_1 = {
2044                 nodes[0].node.send_payment(&route, payment_hash_3, &Some(payment_secret_3), PaymentId(payment_hash_3.0)).unwrap();
2045                 check_added_monitors!(nodes[0], 1);
2046                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2047                 assert_eq!(events.len(), 1);
2048                 SendEvent::from_event(events.remove(0))
2049         };
2050
2051         // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2052         // initial fulfill/CS.
2053         nodes[1].node.claim_funds(payment_preimage_1);
2054         expect_payment_claimed!(nodes[1], payment_hash_1, payment_value_1);
2055         check_added_monitors!(nodes[1], 1);
2056         let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2057
2058         // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2059         // remove the second HTLC when we send the HTLC back from B to A.
2060         nodes[1].node.claim_funds(payment_preimage_2);
2061         expect_payment_claimed!(nodes[1], payment_hash_2, 20_000);
2062         check_added_monitors!(nodes[1], 1);
2063         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2064
2065         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2066         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2067         check_added_monitors!(nodes[0], 1);
2068         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2069         expect_payment_sent_without_paths!(nodes[0], payment_preimage_1);
2070
2071         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2072         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2073         check_added_monitors!(nodes[1], 1);
2074         // B is already AwaitingRAA, so cant generate a CS here
2075         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2076
2077         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2078         check_added_monitors!(nodes[1], 1);
2079         let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2080
2081         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2082         check_added_monitors!(nodes[0], 1);
2083         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2084
2085         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2086         check_added_monitors!(nodes[1], 1);
2087         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2088
2089         // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2090         // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2091         // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2092         // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2093         // on-chain as necessary).
2094         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2095         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2096         check_added_monitors!(nodes[0], 1);
2097         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2098         expect_payment_sent_without_paths!(nodes[0], payment_preimage_2);
2099
2100         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2101         check_added_monitors!(nodes[1], 1);
2102         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2103
2104         expect_pending_htlcs_forwardable!(nodes[1]);
2105         expect_payment_received!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2106
2107         // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2108         // resolve the second HTLC from A's point of view.
2109         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2110         check_added_monitors!(nodes[0], 1);
2111         expect_payment_path_successful!(nodes[0]);
2112         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2113
2114         // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2115         // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2116         let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2117         let send_2 = {
2118                 nodes[1].node.send_payment(&route, payment_hash_4, &Some(payment_secret_4), PaymentId(payment_hash_4.0)).unwrap();
2119                 check_added_monitors!(nodes[1], 1);
2120                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2121                 assert_eq!(events.len(), 1);
2122                 SendEvent::from_event(events.remove(0))
2123         };
2124
2125         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2126         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2127         check_added_monitors!(nodes[0], 1);
2128         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2129
2130         // Now just resolve all the outstanding messages/HTLCs for completeness...
2131
2132         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2133         check_added_monitors!(nodes[1], 1);
2134         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2135
2136         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2137         check_added_monitors!(nodes[1], 1);
2138
2139         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2140         check_added_monitors!(nodes[0], 1);
2141         expect_payment_path_successful!(nodes[0]);
2142         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2143
2144         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2145         check_added_monitors!(nodes[1], 1);
2146         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2147
2148         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2149         check_added_monitors!(nodes[0], 1);
2150
2151         expect_pending_htlcs_forwardable!(nodes[0]);
2152         expect_payment_received!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2153
2154         claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2155         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2156 }
2157
2158 #[test]
2159 fn channel_monitor_network_test() {
2160         // Simple test which builds a network of ChannelManagers, connects them to each other, and
2161         // tests that ChannelMonitor is able to recover from various states.
2162         let chanmon_cfgs = create_chanmon_cfgs(5);
2163         let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2164         let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2165         let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2166
2167         // Create some initial channels
2168         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2169         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2170         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2171         let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2172
2173         // Make sure all nodes are at the same starting height
2174         connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2175         connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2176         connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2177         connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2178         connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2179
2180         // Rebalance the network a bit by relaying one payment through all the channels...
2181         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2182         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2183         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2184         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2185
2186         // Simple case with no pending HTLCs:
2187         nodes[1].node.force_close_broadcasting_latest_txn(&chan_1.2, &nodes[0].node.get_our_node_id()).unwrap();
2188         check_added_monitors!(nodes[1], 1);
2189         check_closed_broadcast!(nodes[1], true);
2190         {
2191                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2192                 assert_eq!(node_txn.len(), 1);
2193                 mine_transaction(&nodes[0], &node_txn[0]);
2194                 check_added_monitors!(nodes[0], 1);
2195                 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
2196         }
2197         check_closed_broadcast!(nodes[0], true);
2198         assert_eq!(nodes[0].node.list_channels().len(), 0);
2199         assert_eq!(nodes[1].node.list_channels().len(), 1);
2200         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2201         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2202
2203         // One pending HTLC is discarded by the force-close:
2204         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[1], &[&nodes[2], &nodes[3]], 3_000_000);
2205
2206         // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2207         // broadcasted until we reach the timelock time).
2208         nodes[1].node.force_close_broadcasting_latest_txn(&chan_2.2, &nodes[2].node.get_our_node_id()).unwrap();
2209         check_closed_broadcast!(nodes[1], true);
2210         check_added_monitors!(nodes[1], 1);
2211         {
2212                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2213                 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2214                 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2215                 mine_transaction(&nodes[2], &node_txn[0]);
2216                 check_added_monitors!(nodes[2], 1);
2217                 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
2218         }
2219         check_closed_broadcast!(nodes[2], true);
2220         assert_eq!(nodes[1].node.list_channels().len(), 0);
2221         assert_eq!(nodes[2].node.list_channels().len(), 1);
2222         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2223         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2224
2225         macro_rules! claim_funds {
2226                 ($node: expr, $prev_node: expr, $preimage: expr, $payment_hash: expr) => {
2227                         {
2228                                 $node.node.claim_funds($preimage);
2229                                 expect_payment_claimed!($node, $payment_hash, 3_000_000);
2230                                 check_added_monitors!($node, 1);
2231
2232                                 let events = $node.node.get_and_clear_pending_msg_events();
2233                                 assert_eq!(events.len(), 1);
2234                                 match events[0] {
2235                                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2236                                                 assert!(update_add_htlcs.is_empty());
2237                                                 assert!(update_fail_htlcs.is_empty());
2238                                                 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2239                                         },
2240                                         _ => panic!("Unexpected event"),
2241                                 };
2242                         }
2243                 }
2244         }
2245
2246         // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2247         // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2248         nodes[2].node.force_close_broadcasting_latest_txn(&chan_3.2, &nodes[3].node.get_our_node_id()).unwrap();
2249         check_added_monitors!(nodes[2], 1);
2250         check_closed_broadcast!(nodes[2], true);
2251         let node2_commitment_txid;
2252         {
2253                 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2254                 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2255                 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2256                 node2_commitment_txid = node_txn[0].txid();
2257
2258                 // Claim the payment on nodes[3], giving it knowledge of the preimage
2259                 claim_funds!(nodes[3], nodes[2], payment_preimage_1, payment_hash_1);
2260                 mine_transaction(&nodes[3], &node_txn[0]);
2261                 check_added_monitors!(nodes[3], 1);
2262                 check_preimage_claim(&nodes[3], &node_txn);
2263         }
2264         check_closed_broadcast!(nodes[3], true);
2265         assert_eq!(nodes[2].node.list_channels().len(), 0);
2266         assert_eq!(nodes[3].node.list_channels().len(), 1);
2267         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
2268         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2269
2270         // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2271         // confusing us in the following tests.
2272         let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2273
2274         // One pending HTLC to time out:
2275         let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[3], &[&nodes[4]], 3_000_000);
2276         // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2277         // buffer space).
2278
2279         let (close_chan_update_1, close_chan_update_2) = {
2280                 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2281                 let events = nodes[3].node.get_and_clear_pending_msg_events();
2282                 assert_eq!(events.len(), 2);
2283                 let close_chan_update_1 = match events[0] {
2284                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2285                                 msg.clone()
2286                         },
2287                         _ => panic!("Unexpected event"),
2288                 };
2289                 match events[1] {
2290                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2291                                 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2292                         },
2293                         _ => panic!("Unexpected event"),
2294                 }
2295                 check_added_monitors!(nodes[3], 1);
2296
2297                 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2298                 {
2299                         let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2300                         node_txn.retain(|tx| {
2301                                 if tx.input[0].previous_output.txid == node2_commitment_txid {
2302                                         false
2303                                 } else { true }
2304                         });
2305                 }
2306
2307                 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2308
2309                 // Claim the payment on nodes[4], giving it knowledge of the preimage
2310                 claim_funds!(nodes[4], nodes[3], payment_preimage_2, payment_hash_2);
2311
2312                 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2313                 let events = nodes[4].node.get_and_clear_pending_msg_events();
2314                 assert_eq!(events.len(), 2);
2315                 let close_chan_update_2 = match events[0] {
2316                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2317                                 msg.clone()
2318                         },
2319                         _ => panic!("Unexpected event"),
2320                 };
2321                 match events[1] {
2322                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2323                                 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2324                         },
2325                         _ => panic!("Unexpected event"),
2326                 }
2327                 check_added_monitors!(nodes[4], 1);
2328                 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2329
2330                 mine_transaction(&nodes[4], &node_txn[0]);
2331                 check_preimage_claim(&nodes[4], &node_txn);
2332                 (close_chan_update_1, close_chan_update_2)
2333         };
2334         nodes[3].gossip_sync.handle_channel_update(&close_chan_update_2).unwrap();
2335         nodes[4].gossip_sync.handle_channel_update(&close_chan_update_1).unwrap();
2336         assert_eq!(nodes[3].node.list_channels().len(), 0);
2337         assert_eq!(nodes[4].node.list_channels().len(), 0);
2338
2339         assert_eq!(nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon),
2340                 ChannelMonitorUpdateStatus::Completed);
2341         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2342         check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed);
2343 }
2344
2345 #[test]
2346 fn test_justice_tx() {
2347         // Test justice txn built on revoked HTLC-Success tx, against both sides
2348         let mut alice_config = UserConfig::default();
2349         alice_config.channel_handshake_config.announced_channel = true;
2350         alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2351         alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2352         let mut bob_config = UserConfig::default();
2353         bob_config.channel_handshake_config.announced_channel = true;
2354         bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2355         bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2356         let user_cfgs = [Some(alice_config), Some(bob_config)];
2357         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2358         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2359         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2360         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2361         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2362         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2363         *nodes[0].connect_style.borrow_mut() = ConnectStyle::FullBlockViaListen;
2364         // Create some new channels:
2365         let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2366
2367         // A pending HTLC which will be revoked:
2368         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2369         // Get the will-be-revoked local txn from nodes[0]
2370         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2371         assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2372         assert_eq!(revoked_local_txn[0].input.len(), 1);
2373         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2374         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2375         assert_eq!(revoked_local_txn[1].input.len(), 1);
2376         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2377         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2378         // Revoke the old state
2379         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2380
2381         {
2382                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2383                 {
2384                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2385                         assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2386                         assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2387
2388                         check_spends!(node_txn[0], revoked_local_txn[0]);
2389                         node_txn.swap_remove(0);
2390                         node_txn.truncate(1);
2391                 }
2392                 check_added_monitors!(nodes[1], 1);
2393                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2394                 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2395
2396                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2397                 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2398                 // Verify broadcast of revoked HTLC-timeout
2399                 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2400                 check_added_monitors!(nodes[0], 1);
2401                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2402                 // Broadcast revoked HTLC-timeout on node 1
2403                 mine_transaction(&nodes[1], &node_txn[1]);
2404                 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2405         }
2406         get_announce_close_broadcast_events(&nodes, 0, 1);
2407
2408         assert_eq!(nodes[0].node.list_channels().len(), 0);
2409         assert_eq!(nodes[1].node.list_channels().len(), 0);
2410
2411         // We test justice_tx build by A on B's revoked HTLC-Success tx
2412         // Create some new channels:
2413         let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2414         {
2415                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2416                 node_txn.clear();
2417         }
2418
2419         // A pending HTLC which will be revoked:
2420         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2421         // Get the will-be-revoked local txn from B
2422         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2423         assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2424         assert_eq!(revoked_local_txn[0].input.len(), 1);
2425         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2426         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2427         // Revoke the old state
2428         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2429         {
2430                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2431                 {
2432                         let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2433                         assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2434                         assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2435
2436                         check_spends!(node_txn[0], revoked_local_txn[0]);
2437                         node_txn.swap_remove(0);
2438                 }
2439                 check_added_monitors!(nodes[0], 1);
2440                 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2441
2442                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2443                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2444                 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2445                 check_added_monitors!(nodes[1], 1);
2446                 mine_transaction(&nodes[0], &node_txn[1]);
2447                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2448                 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2449         }
2450         get_announce_close_broadcast_events(&nodes, 0, 1);
2451         assert_eq!(nodes[0].node.list_channels().len(), 0);
2452         assert_eq!(nodes[1].node.list_channels().len(), 0);
2453 }
2454
2455 #[test]
2456 fn revoked_output_claim() {
2457         // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2458         // transaction is broadcast by its counterparty
2459         let chanmon_cfgs = create_chanmon_cfgs(2);
2460         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2461         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2462         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2463         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2464         // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2465         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2466         assert_eq!(revoked_local_txn.len(), 1);
2467         // Only output is the full channel value back to nodes[0]:
2468         assert_eq!(revoked_local_txn[0].output.len(), 1);
2469         // Send a payment through, updating everyone's latest commitment txn
2470         send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2471
2472         // Inform nodes[1] that nodes[0] broadcast a stale tx
2473         mine_transaction(&nodes[1], &revoked_local_txn[0]);
2474         check_added_monitors!(nodes[1], 1);
2475         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2476         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2477         assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2478
2479         check_spends!(node_txn[0], revoked_local_txn[0]);
2480         check_spends!(node_txn[1], chan_1.3);
2481
2482         // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2483         mine_transaction(&nodes[0], &revoked_local_txn[0]);
2484         get_announce_close_broadcast_events(&nodes, 0, 1);
2485         check_added_monitors!(nodes[0], 1);
2486         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2487 }
2488
2489 #[test]
2490 fn claim_htlc_outputs_shared_tx() {
2491         // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2492         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2493         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2494         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2495         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2496         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2497
2498         // Create some new channel:
2499         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2500
2501         // Rebalance the network to generate htlc in the two directions
2502         send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2503         // 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
2504         let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2505         let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2506
2507         // Get the will-be-revoked local txn from node[0]
2508         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2509         assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2510         assert_eq!(revoked_local_txn[0].input.len(), 1);
2511         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2512         assert_eq!(revoked_local_txn[1].input.len(), 1);
2513         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2514         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2515         check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2516
2517         //Revoke the old state
2518         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2519
2520         {
2521                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2522                 check_added_monitors!(nodes[0], 1);
2523                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2524                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2525                 check_added_monitors!(nodes[1], 1);
2526                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2527                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2528                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2529
2530                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2531                 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment
2532
2533                 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2534                 check_spends!(node_txn[0], revoked_local_txn[0]);
2535
2536                 let mut witness_lens = BTreeSet::new();
2537                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2538                 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2539                 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2540                 assert_eq!(witness_lens.len(), 3);
2541                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2542                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2543                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2544
2545                 // Next nodes[1] broadcasts its current local tx state:
2546                 assert_eq!(node_txn[1].input.len(), 1);
2547                 check_spends!(node_txn[1], chan_1.3);
2548
2549                 // Finally, mine the penalty transaction and check that we get an HTLC failure after
2550                 // ANTI_REORG_DELAY confirmations.
2551                 mine_transaction(&nodes[1], &node_txn[0]);
2552                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2553                 expect_payment_failed!(nodes[1], payment_hash_2, false);
2554         }
2555         get_announce_close_broadcast_events(&nodes, 0, 1);
2556         assert_eq!(nodes[0].node.list_channels().len(), 0);
2557         assert_eq!(nodes[1].node.list_channels().len(), 0);
2558 }
2559
2560 #[test]
2561 fn claim_htlc_outputs_single_tx() {
2562         // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2563         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2564         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2565         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2566         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2567         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2568
2569         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2570
2571         // Rebalance the network to generate htlc in the two directions
2572         send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2573         // 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
2574         // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2575         let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2576         let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2577
2578         // Get the will-be-revoked local txn from node[0]
2579         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2580
2581         //Revoke the old state
2582         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2583
2584         {
2585                 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2586                 check_added_monitors!(nodes[0], 1);
2587                 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2588                 check_added_monitors!(nodes[1], 1);
2589                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2590                 let mut events = nodes[0].node.get_and_clear_pending_events();
2591                 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2592                 match events.last().unwrap() {
2593                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2594                         _ => panic!("Unexpected event"),
2595                 }
2596
2597                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2598                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2599
2600                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2601                 assert!(node_txn.len() == 9 || node_txn.len() == 10);
2602
2603                 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2604                 assert_eq!(node_txn[0].input.len(), 1);
2605                 check_spends!(node_txn[0], chan_1.3);
2606                 assert_eq!(node_txn[1].input.len(), 1);
2607                 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2608                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2609                 check_spends!(node_txn[1], node_txn[0]);
2610
2611                 // Justice transactions are indices 1-2-4
2612                 assert_eq!(node_txn[2].input.len(), 1);
2613                 assert_eq!(node_txn[3].input.len(), 1);
2614                 assert_eq!(node_txn[4].input.len(), 1);
2615
2616                 check_spends!(node_txn[2], revoked_local_txn[0]);
2617                 check_spends!(node_txn[3], revoked_local_txn[0]);
2618                 check_spends!(node_txn[4], revoked_local_txn[0]);
2619
2620                 let mut witness_lens = BTreeSet::new();
2621                 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2622                 witness_lens.insert(node_txn[3].input[0].witness.last().unwrap().len());
2623                 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2624                 assert_eq!(witness_lens.len(), 3);
2625                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2626                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2627                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2628
2629                 // Finally, mine the penalty transactions and check that we get an HTLC failure after
2630                 // ANTI_REORG_DELAY confirmations.
2631                 mine_transaction(&nodes[1], &node_txn[2]);
2632                 mine_transaction(&nodes[1], &node_txn[3]);
2633                 mine_transaction(&nodes[1], &node_txn[4]);
2634                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2635                 expect_payment_failed!(nodes[1], payment_hash_2, false);
2636         }
2637         get_announce_close_broadcast_events(&nodes, 0, 1);
2638         assert_eq!(nodes[0].node.list_channels().len(), 0);
2639         assert_eq!(nodes[1].node.list_channels().len(), 0);
2640 }
2641
2642 #[test]
2643 fn test_htlc_on_chain_success() {
2644         // Test that in case of a unilateral close onchain, we detect the state of output and pass
2645         // the preimage backward accordingly. So here we test that ChannelManager is
2646         // broadcasting the right event to other nodes in payment path.
2647         // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2648         // A --------------------> B ----------------------> C (preimage)
2649         // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2650         // commitment transaction was broadcast.
2651         // Then, B should learn the preimage from said transactions, attempting to claim backwards
2652         // towards B.
2653         // B should be able to claim via preimage if A then broadcasts its local tx.
2654         // Finally, when A sees B's latest local commitment transaction it should be able to claim
2655         // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2656         // PaymentSent event).
2657
2658         let chanmon_cfgs = create_chanmon_cfgs(3);
2659         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2660         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2661         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2662
2663         // Create some initial channels
2664         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2665         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2666
2667         // Ensure all nodes are at the same height
2668         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2669         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2670         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2671         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2672
2673         // Rebalance the network a bit by relaying one payment through all the channels...
2674         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2675         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2676
2677         let (our_payment_preimage, payment_hash_1, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2678         let (our_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2679
2680         // Broadcast legit commitment tx from C on B's chain
2681         // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2682         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2683         assert_eq!(commitment_tx.len(), 1);
2684         check_spends!(commitment_tx[0], chan_2.3);
2685         nodes[2].node.claim_funds(our_payment_preimage);
2686         expect_payment_claimed!(nodes[2], payment_hash_1, 3_000_000);
2687         nodes[2].node.claim_funds(our_payment_preimage_2);
2688         expect_payment_claimed!(nodes[2], payment_hash_2, 3_000_000);
2689         check_added_monitors!(nodes[2], 2);
2690         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2691         assert!(updates.update_add_htlcs.is_empty());
2692         assert!(updates.update_fail_htlcs.is_empty());
2693         assert!(updates.update_fail_malformed_htlcs.is_empty());
2694         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2695
2696         mine_transaction(&nodes[2], &commitment_tx[0]);
2697         check_closed_broadcast!(nodes[2], true);
2698         check_added_monitors!(nodes[2], 1);
2699         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2700         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 3 (commitment tx, 2*htlc-success tx), ChannelMonitor : 2 (2 * HTLC-Success tx)
2701         assert_eq!(node_txn.len(), 5);
2702         assert_eq!(node_txn[0], node_txn[3]);
2703         assert_eq!(node_txn[1], node_txn[4]);
2704         assert_eq!(node_txn[2], commitment_tx[0]);
2705         check_spends!(node_txn[0], commitment_tx[0]);
2706         check_spends!(node_txn[1], commitment_tx[0]);
2707         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2708         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2709         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2710         assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2711         assert_eq!(node_txn[0].lock_time.0, 0);
2712         assert_eq!(node_txn[1].lock_time.0, 0);
2713
2714         // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2715         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
2716         connect_block(&nodes[1], &Block { header, txdata: node_txn});
2717         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2718         {
2719                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2720                 assert_eq!(added_monitors.len(), 1);
2721                 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2722                 added_monitors.clear();
2723         }
2724         let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2725         assert_eq!(forwarded_events.len(), 3);
2726         match forwarded_events[0] {
2727                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2728                 _ => panic!("Unexpected event"),
2729         }
2730         let chan_id = Some(chan_1.2);
2731         match forwarded_events[1] {
2732                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
2733                         assert_eq!(fee_earned_msat, Some(1000));
2734                         assert_eq!(prev_channel_id, chan_id);
2735                         assert_eq!(claim_from_onchain_tx, true);
2736                         assert_eq!(next_channel_id, Some(chan_2.2));
2737                 },
2738                 _ => panic!()
2739         }
2740         match forwarded_events[2] {
2741                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
2742                         assert_eq!(fee_earned_msat, Some(1000));
2743                         assert_eq!(prev_channel_id, chan_id);
2744                         assert_eq!(claim_from_onchain_tx, true);
2745                         assert_eq!(next_channel_id, Some(chan_2.2));
2746                 },
2747                 _ => panic!()
2748         }
2749         let events = nodes[1].node.get_and_clear_pending_msg_events();
2750         {
2751                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2752                 assert_eq!(added_monitors.len(), 2);
2753                 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2754                 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2755                 added_monitors.clear();
2756         }
2757         assert_eq!(events.len(), 3);
2758         match events[0] {
2759                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2760                 _ => panic!("Unexpected event"),
2761         }
2762         match events[1] {
2763                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2764                 _ => panic!("Unexpected event"),
2765         }
2766
2767         match events[2] {
2768                 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, .. } } => {
2769                         assert!(update_add_htlcs.is_empty());
2770                         assert!(update_fail_htlcs.is_empty());
2771                         assert_eq!(update_fulfill_htlcs.len(), 1);
2772                         assert!(update_fail_malformed_htlcs.is_empty());
2773                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2774                 },
2775                 _ => panic!("Unexpected event"),
2776         };
2777         macro_rules! check_tx_local_broadcast {
2778                 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2779                         let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2780                         assert_eq!(node_txn.len(), 3);
2781                         // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2782                         // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2783                         check_spends!(node_txn[1], $commitment_tx);
2784                         check_spends!(node_txn[2], $commitment_tx);
2785                         assert_ne!(node_txn[1].lock_time.0, 0);
2786                         assert_ne!(node_txn[2].lock_time.0, 0);
2787                         if $htlc_offered {
2788                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2789                                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2790                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2791                                 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2792                         } else {
2793                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2794                                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2795                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2796                                 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2797                         }
2798                         check_spends!(node_txn[0], $chan_tx);
2799                         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2800                         node_txn.clear();
2801                 } }
2802         }
2803         // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2804         // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2805         // timeout-claim of the output that nodes[2] just claimed via success.
2806         check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2807
2808         // Broadcast legit commitment tx from A on B's chain
2809         // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
2810         let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2811         check_spends!(node_a_commitment_tx[0], chan_1.3);
2812         mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2813         check_closed_broadcast!(nodes[1], true);
2814         check_added_monitors!(nodes[1], 1);
2815         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2816         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2817         assert_eq!(node_txn.len(), 6); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 3 (HTLC-Success, 2* RBF bumps of above HTLC txn)
2818         let commitment_spend =
2819                 if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2820                         check_spends!(node_txn[1], commitment_tx[0]);
2821                         check_spends!(node_txn[2], commitment_tx[0]);
2822                         assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2823                         &node_txn[0]
2824                 } else {
2825                         check_spends!(node_txn[0], commitment_tx[0]);
2826                         check_spends!(node_txn[1], commitment_tx[0]);
2827                         assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2828                         &node_txn[2]
2829                 };
2830
2831         check_spends!(commitment_spend, node_a_commitment_tx[0]);
2832         assert_eq!(commitment_spend.input.len(), 2);
2833         assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2834         assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2835         assert_eq!(commitment_spend.lock_time.0, 0);
2836         assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2837         check_spends!(node_txn[3], chan_1.3);
2838         assert_eq!(node_txn[3].input[0].witness.clone().last().unwrap().len(), 71);
2839         check_spends!(node_txn[4], node_txn[3]);
2840         check_spends!(node_txn[5], node_txn[3]);
2841         // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2842         // we already checked the same situation with A.
2843
2844         // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2845         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
2846         connect_block(&nodes[0], &Block { header, txdata: vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()] });
2847         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2848         check_closed_broadcast!(nodes[0], true);
2849         check_added_monitors!(nodes[0], 1);
2850         let events = nodes[0].node.get_and_clear_pending_events();
2851         assert_eq!(events.len(), 5);
2852         let mut first_claimed = false;
2853         for event in events {
2854                 match event {
2855                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
2856                                 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
2857                                         assert!(!first_claimed);
2858                                         first_claimed = true;
2859                                 } else {
2860                                         assert_eq!(payment_preimage, our_payment_preimage_2);
2861                                         assert_eq!(payment_hash, payment_hash_2);
2862                                 }
2863                         },
2864                         Event::PaymentPathSuccessful { .. } => {},
2865                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
2866                         _ => panic!("Unexpected event"),
2867                 }
2868         }
2869         check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0], chan_1.3);
2870 }
2871
2872 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2873         // Test that in case of a unilateral close onchain, we detect the state of output and
2874         // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2875         // broadcasting the right event to other nodes in payment path.
2876         // A ------------------> B ----------------------> C (timeout)
2877         //    B's commitment tx                 C's commitment tx
2878         //            \                                  \
2879         //         B's HTLC timeout tx               B's timeout tx
2880
2881         let chanmon_cfgs = create_chanmon_cfgs(3);
2882         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2883         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2884         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2885         *nodes[0].connect_style.borrow_mut() = connect_style;
2886         *nodes[1].connect_style.borrow_mut() = connect_style;
2887         *nodes[2].connect_style.borrow_mut() = connect_style;
2888
2889         // Create some intial channels
2890         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2891         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2892
2893         // Rebalance the network a bit by relaying one payment thorugh all the channels...
2894         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2895         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2896
2897         let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2898
2899         // Broadcast legit commitment tx from C on B's chain
2900         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2901         check_spends!(commitment_tx[0], chan_2.3);
2902         nodes[2].node.fail_htlc_backwards(&payment_hash);
2903         check_added_monitors!(nodes[2], 0);
2904         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }]);
2905         check_added_monitors!(nodes[2], 1);
2906
2907         let events = nodes[2].node.get_and_clear_pending_msg_events();
2908         assert_eq!(events.len(), 1);
2909         match events[0] {
2910                 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, .. } } => {
2911                         assert!(update_add_htlcs.is_empty());
2912                         assert!(!update_fail_htlcs.is_empty());
2913                         assert!(update_fulfill_htlcs.is_empty());
2914                         assert!(update_fail_malformed_htlcs.is_empty());
2915                         assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2916                 },
2917                 _ => panic!("Unexpected event"),
2918         };
2919         mine_transaction(&nodes[2], &commitment_tx[0]);
2920         check_closed_broadcast!(nodes[2], true);
2921         check_added_monitors!(nodes[2], 1);
2922         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2923         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2924         assert_eq!(node_txn.len(), 1);
2925         check_spends!(node_txn[0], chan_2.3);
2926         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2927
2928         // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2929         // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2930         connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2931         mine_transaction(&nodes[1], &commitment_tx[0]);
2932         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2933         let timeout_tx;
2934         {
2935                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2936                 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
2937                 assert_eq!(node_txn[0], node_txn[3]);
2938                 assert_eq!(node_txn[1], node_txn[4]);
2939
2940                 check_spends!(node_txn[2], commitment_tx[0]);
2941                 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2942
2943                 check_spends!(node_txn[0], chan_2.3);
2944                 check_spends!(node_txn[1], node_txn[0]);
2945                 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2946                 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2947
2948                 timeout_tx = node_txn[2].clone();
2949                 node_txn.clear();
2950         }
2951
2952         mine_transaction(&nodes[1], &timeout_tx);
2953         check_added_monitors!(nodes[1], 1);
2954         check_closed_broadcast!(nodes[1], true);
2955
2956         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2957
2958         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 }]);
2959         check_added_monitors!(nodes[1], 1);
2960         let events = nodes[1].node.get_and_clear_pending_msg_events();
2961         assert_eq!(events.len(), 1);
2962         match events[0] {
2963                 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, .. } } => {
2964                         assert!(update_add_htlcs.is_empty());
2965                         assert!(!update_fail_htlcs.is_empty());
2966                         assert!(update_fulfill_htlcs.is_empty());
2967                         assert!(update_fail_malformed_htlcs.is_empty());
2968                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2969                 },
2970                 _ => panic!("Unexpected event"),
2971         };
2972
2973         // Broadcast legit commitment tx from B on A's chain
2974         let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
2975         check_spends!(commitment_tx[0], chan_1.3);
2976
2977         mine_transaction(&nodes[0], &commitment_tx[0]);
2978         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2979
2980         check_closed_broadcast!(nodes[0], true);
2981         check_added_monitors!(nodes[0], 1);
2982         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2983         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 commitment tx, ChannelMonitor : 1 timeout tx
2984         assert_eq!(node_txn.len(), 2);
2985         check_spends!(node_txn[0], chan_1.3);
2986         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2987         check_spends!(node_txn[1], commitment_tx[0]);
2988         assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2989 }
2990
2991 #[test]
2992 fn test_htlc_on_chain_timeout() {
2993         do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
2994         do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
2995         do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
2996 }
2997
2998 #[test]
2999 fn test_simple_commitment_revoked_fail_backward() {
3000         // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3001         // and fail backward accordingly.
3002
3003         let chanmon_cfgs = create_chanmon_cfgs(3);
3004         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3005         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3006         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3007
3008         // Create some initial channels
3009         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3010         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3011
3012         let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3013         // Get the will-be-revoked local txn from nodes[2]
3014         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3015         // Revoke the old state
3016         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3017
3018         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3019
3020         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3021         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3022         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3023         check_added_monitors!(nodes[1], 1);
3024         check_closed_broadcast!(nodes[1], true);
3025
3026         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 }]);
3027         check_added_monitors!(nodes[1], 1);
3028         let events = nodes[1].node.get_and_clear_pending_msg_events();
3029         assert_eq!(events.len(), 1);
3030         match events[0] {
3031                 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, .. } } => {
3032                         assert!(update_add_htlcs.is_empty());
3033                         assert_eq!(update_fail_htlcs.len(), 1);
3034                         assert!(update_fulfill_htlcs.is_empty());
3035                         assert!(update_fail_malformed_htlcs.is_empty());
3036                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3037
3038                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3039                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3040                         expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3041                 },
3042                 _ => panic!("Unexpected event"),
3043         }
3044 }
3045
3046 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3047         // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3048         // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3049         // commitment transaction anymore.
3050         // To do this, we have the peer which will broadcast a revoked commitment transaction send
3051         // a number of update_fail/commitment_signed updates without ever sending the RAA in
3052         // response to our commitment_signed. This is somewhat misbehavior-y, though not
3053         // technically disallowed and we should probably handle it reasonably.
3054         // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3055         // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3056         // transactions:
3057         // * Once we move it out of our holding cell/add it, we will immediately include it in a
3058         //   commitment_signed (implying it will be in the latest remote commitment transaction).
3059         // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3060         //   and once they revoke the previous commitment transaction (allowing us to send a new
3061         //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3062         let chanmon_cfgs = create_chanmon_cfgs(3);
3063         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3064         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3065         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3066
3067         // Create some initial channels
3068         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3069         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3070
3071         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 });
3072         // Get the will-be-revoked local txn from nodes[2]
3073         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3074         assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3075         // Revoke the old state
3076         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3077
3078         let value = if use_dust {
3079                 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3080                 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3081                 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3082         } else { 3000000 };
3083
3084         let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3085         let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3086         let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3087
3088         nodes[2].node.fail_htlc_backwards(&first_payment_hash);
3089         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
3090         check_added_monitors!(nodes[2], 1);
3091         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3092         assert!(updates.update_add_htlcs.is_empty());
3093         assert!(updates.update_fulfill_htlcs.is_empty());
3094         assert!(updates.update_fail_malformed_htlcs.is_empty());
3095         assert_eq!(updates.update_fail_htlcs.len(), 1);
3096         assert!(updates.update_fee.is_none());
3097         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3098         let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3099         // Drop the last RAA from 3 -> 2
3100
3101         nodes[2].node.fail_htlc_backwards(&second_payment_hash);
3102         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: second_payment_hash }]);
3103         check_added_monitors!(nodes[2], 1);
3104         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3105         assert!(updates.update_add_htlcs.is_empty());
3106         assert!(updates.update_fulfill_htlcs.is_empty());
3107         assert!(updates.update_fail_malformed_htlcs.is_empty());
3108         assert_eq!(updates.update_fail_htlcs.len(), 1);
3109         assert!(updates.update_fee.is_none());
3110         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3111         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3112         check_added_monitors!(nodes[1], 1);
3113         // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3114         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3115         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3116         check_added_monitors!(nodes[2], 1);
3117
3118         nodes[2].node.fail_htlc_backwards(&third_payment_hash);
3119         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: third_payment_hash }]);
3120         check_added_monitors!(nodes[2], 1);
3121         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3122         assert!(updates.update_add_htlcs.is_empty());
3123         assert!(updates.update_fulfill_htlcs.is_empty());
3124         assert!(updates.update_fail_malformed_htlcs.is_empty());
3125         assert_eq!(updates.update_fail_htlcs.len(), 1);
3126         assert!(updates.update_fee.is_none());
3127         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3128         // At this point first_payment_hash has dropped out of the latest two commitment
3129         // transactions that nodes[1] is tracking...
3130         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3131         check_added_monitors!(nodes[1], 1);
3132         // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3133         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3134         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3135         check_added_monitors!(nodes[2], 1);
3136
3137         // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3138         // on nodes[2]'s RAA.
3139         let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3140         nodes[1].node.send_payment(&route, fourth_payment_hash, &Some(fourth_payment_secret), PaymentId(fourth_payment_hash.0)).unwrap();
3141         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3142         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3143         check_added_monitors!(nodes[1], 0);
3144
3145         if deliver_bs_raa {
3146                 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3147                 // One monitor for the new revocation preimage, no second on as we won't generate a new
3148                 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3149                 check_added_monitors!(nodes[1], 1);
3150                 let events = nodes[1].node.get_and_clear_pending_events();
3151                 assert_eq!(events.len(), 2);
3152                 match events[0] {
3153                         Event::PendingHTLCsForwardable { .. } => { },
3154                         _ => panic!("Unexpected event"),
3155                 };
3156                 match events[1] {
3157                         Event::HTLCHandlingFailed { .. } => { },
3158                         _ => panic!("Unexpected event"),
3159                 }
3160                 // Deliberately don't process the pending fail-back so they all fail back at once after
3161                 // block connection just like the !deliver_bs_raa case
3162         }
3163
3164         let mut failed_htlcs = HashSet::new();
3165         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3166
3167         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3168         check_added_monitors!(nodes[1], 1);
3169         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3170
3171         let events = nodes[1].node.get_and_clear_pending_events();
3172         assert_eq!(events.len(), if deliver_bs_raa { 2 + nodes.len() - 1 } else { 3 + nodes.len() });
3173         match events[0] {
3174                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3175                 _ => panic!("Unexepected event"),
3176         }
3177         match events[1] {
3178                 Event::PaymentPathFailed { ref payment_hash, .. } => {
3179                         assert_eq!(*payment_hash, fourth_payment_hash);
3180                 },
3181                 _ => panic!("Unexpected event"),
3182         }
3183         if !deliver_bs_raa {
3184                 match events[2] {
3185                         Event::PendingHTLCsForwardable { .. } => { },
3186                         _ => panic!("Unexpected event"),
3187                 };
3188                 nodes[1].node.abandon_payment(PaymentId(fourth_payment_hash.0));
3189                 let payment_failed_events = nodes[1].node.get_and_clear_pending_events();
3190                 assert_eq!(payment_failed_events.len(), 1);
3191                 match payment_failed_events[0] {
3192                         Event::PaymentFailed { ref payment_hash, .. } => {
3193                                 assert_eq!(*payment_hash, fourth_payment_hash);
3194                         },
3195                         _ => panic!("Unexpected event"),
3196                 }
3197         }
3198         nodes[1].node.process_pending_htlc_forwards();
3199         check_added_monitors!(nodes[1], 1);
3200
3201         let events = nodes[1].node.get_and_clear_pending_msg_events();
3202         assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3203         match events[if deliver_bs_raa { 1 } else { 0 }] {
3204                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3205                 _ => panic!("Unexpected event"),
3206         }
3207         match events[if deliver_bs_raa { 2 } else { 1 }] {
3208                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3209                         assert_eq!(channel_id, chan_2.2);
3210                         assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3211                 },
3212                 _ => panic!("Unexpected event"),
3213         }
3214         if deliver_bs_raa {
3215                 match events[0] {
3216                         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, .. } } => {
3217                                 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3218                                 assert_eq!(update_add_htlcs.len(), 1);
3219                                 assert!(update_fulfill_htlcs.is_empty());
3220                                 assert!(update_fail_htlcs.is_empty());
3221                                 assert!(update_fail_malformed_htlcs.is_empty());
3222                         },
3223                         _ => panic!("Unexpected event"),
3224                 }
3225         }
3226         match events[if deliver_bs_raa { 3 } else { 2 }] {
3227                 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, .. } } => {
3228                         assert!(update_add_htlcs.is_empty());
3229                         assert_eq!(update_fail_htlcs.len(), 3);
3230                         assert!(update_fulfill_htlcs.is_empty());
3231                         assert!(update_fail_malformed_htlcs.is_empty());
3232                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3233
3234                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3235                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3236                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3237
3238                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3239
3240                         let events = nodes[0].node.get_and_clear_pending_events();
3241                         assert_eq!(events.len(), 3);
3242                         match events[0] {
3243                                 Event::PaymentPathFailed { ref payment_hash, ref network_update, .. } => {
3244                                         assert!(failed_htlcs.insert(payment_hash.0));
3245                                         // If we delivered B's RAA we got an unknown preimage error, not something
3246                                         // that we should update our routing table for.
3247                                         if !deliver_bs_raa {
3248                                                 assert!(network_update.is_some());
3249                                         }
3250                                 },
3251                                 _ => panic!("Unexpected event"),
3252                         }
3253                         match events[1] {
3254                                 Event::PaymentPathFailed { ref payment_hash, ref network_update, .. } => {
3255                                         assert!(failed_htlcs.insert(payment_hash.0));
3256                                         assert!(network_update.is_some());
3257                                 },
3258                                 _ => panic!("Unexpected event"),
3259                         }
3260                         match events[2] {
3261                                 Event::PaymentPathFailed { ref payment_hash, ref network_update, .. } => {
3262                                         assert!(failed_htlcs.insert(payment_hash.0));
3263                                         assert!(network_update.is_some());
3264                                 },
3265                                 _ => panic!("Unexpected event"),
3266                         }
3267                 },
3268                 _ => panic!("Unexpected event"),
3269         }
3270
3271         assert!(failed_htlcs.contains(&first_payment_hash.0));
3272         assert!(failed_htlcs.contains(&second_payment_hash.0));
3273         assert!(failed_htlcs.contains(&third_payment_hash.0));
3274 }
3275
3276 #[test]
3277 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3278         do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3279         do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3280         do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3281         do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3282 }
3283
3284 #[test]
3285 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3286         do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3287         do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3288         do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3289         do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3290 }
3291
3292 #[test]
3293 fn fail_backward_pending_htlc_upon_channel_failure() {
3294         let chanmon_cfgs = create_chanmon_cfgs(2);
3295         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3296         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3297         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3298         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());
3299
3300         // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3301         {
3302                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3303                 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
3304                 check_added_monitors!(nodes[0], 1);
3305
3306                 let payment_event = {
3307                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3308                         assert_eq!(events.len(), 1);
3309                         SendEvent::from_event(events.remove(0))
3310                 };
3311                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3312                 assert_eq!(payment_event.msgs.len(), 1);
3313         }
3314
3315         // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3316         let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3317         {
3318                 nodes[0].node.send_payment(&route, failed_payment_hash, &Some(failed_payment_secret), PaymentId(failed_payment_hash.0)).unwrap();
3319                 check_added_monitors!(nodes[0], 0);
3320
3321                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3322         }
3323
3324         // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3325         {
3326                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3327
3328                 let secp_ctx = Secp256k1::new();
3329                 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3330                 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3331                 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &Some(payment_secret), current_height, &None).unwrap();
3332                 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3333                 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3334
3335                 // Send a 0-msat update_add_htlc to fail the channel.
3336                 let update_add_htlc = msgs::UpdateAddHTLC {
3337                         channel_id: chan.2,
3338                         htlc_id: 0,
3339                         amount_msat: 0,
3340                         payment_hash,
3341                         cltv_expiry,
3342                         onion_routing_packet,
3343                 };
3344                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3345         }
3346         let events = nodes[0].node.get_and_clear_pending_events();
3347         assert_eq!(events.len(), 2);
3348         // Check that Alice fails backward the pending HTLC from the second payment.
3349         match events[0] {
3350                 Event::PaymentPathFailed { payment_hash, .. } => {
3351                         assert_eq!(payment_hash, failed_payment_hash);
3352                 },
3353                 _ => panic!("Unexpected event"),
3354         }
3355         match events[1] {
3356                 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3357                         assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3358                 },
3359                 _ => panic!("Unexpected event {:?}", events[1]),
3360         }
3361         check_closed_broadcast!(nodes[0], true);
3362         check_added_monitors!(nodes[0], 1);
3363 }
3364
3365 #[test]
3366 fn test_htlc_ignore_latest_remote_commitment() {
3367         // Test that HTLC transactions spending the latest remote commitment transaction are simply
3368         // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3369         let chanmon_cfgs = create_chanmon_cfgs(2);
3370         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3371         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3372         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
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         header.prev_blockhash = header.block_hash();
3395         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[2].clone()]});
3396 }
3397
3398 #[test]
3399 fn test_force_close_fail_back() {
3400         // Check which HTLCs are failed-backwards on channel force-closure
3401         let chanmon_cfgs = create_chanmon_cfgs(3);
3402         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3403         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3404         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3405         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3406         create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3407
3408         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3409
3410         let mut payment_event = {
3411                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
3412                 check_added_monitors!(nodes[0], 1);
3413
3414                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3415                 assert_eq!(events.len(), 1);
3416                 SendEvent::from_event(events.remove(0))
3417         };
3418
3419         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3420         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3421
3422         expect_pending_htlcs_forwardable!(nodes[1]);
3423
3424         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3425         assert_eq!(events_2.len(), 1);
3426         payment_event = SendEvent::from_event(events_2.remove(0));
3427         assert_eq!(payment_event.msgs.len(), 1);
3428
3429         check_added_monitors!(nodes[1], 1);
3430         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3431         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3432         check_added_monitors!(nodes[2], 1);
3433         let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3434
3435         // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3436         // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3437         // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3438
3439         nodes[2].node.force_close_broadcasting_latest_txn(&payment_event.commitment_msg.channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3440         check_closed_broadcast!(nodes[2], true);
3441         check_added_monitors!(nodes[2], 1);
3442         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
3443         let tx = {
3444                 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3445                 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3446                 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3447                 // back to nodes[1] upon timeout otherwise.
3448                 assert_eq!(node_txn.len(), 1);
3449                 node_txn.remove(0)
3450         };
3451
3452         mine_transaction(&nodes[1], &tx);
3453
3454         // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3455         check_closed_broadcast!(nodes[1], true);
3456         check_added_monitors!(nodes[1], 1);
3457         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3458
3459         // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3460         {
3461                 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3462                         .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);
3463         }
3464         mine_transaction(&nodes[2], &tx);
3465         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3466         assert_eq!(node_txn.len(), 1);
3467         assert_eq!(node_txn[0].input.len(), 1);
3468         assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3469         assert_eq!(node_txn[0].lock_time.0, 0); // Must be an HTLC-Success
3470         assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3471
3472         check_spends!(node_txn[0], tx);
3473 }
3474
3475 #[test]
3476 fn test_dup_events_on_peer_disconnect() {
3477         // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3478         // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3479         // as we used to generate the event immediately upon receipt of the payment preimage in the
3480         // update_fulfill_htlc message.
3481
3482         let chanmon_cfgs = create_chanmon_cfgs(2);
3483         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3484         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3485         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3486         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3487
3488         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3489
3490         nodes[1].node.claim_funds(payment_preimage);
3491         expect_payment_claimed!(nodes[1], payment_hash, 1_000_000);
3492         check_added_monitors!(nodes[1], 1);
3493         let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3494         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3495         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
3496
3497         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3498         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3499
3500         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3501         expect_payment_path_successful!(nodes[0]);
3502 }
3503
3504 #[test]
3505 fn test_peer_disconnected_before_funding_broadcasted() {
3506         // Test that channels are closed with `ClosureReason::DisconnectedPeer` if the peer disconnects
3507         // before the funding transaction has been broadcasted.
3508         let chanmon_cfgs = create_chanmon_cfgs(2);
3509         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3510         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3511         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3512
3513         // Open a channel between `nodes[0]` and `nodes[1]`, for which the funding transaction is never
3514         // broadcasted, even though it's created by `nodes[0]`.
3515         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();
3516         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
3517         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_channel);
3518         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
3519         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_channel);
3520
3521         let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
3522         assert_eq!(temporary_channel_id, expected_temporary_channel_id);
3523
3524         assert!(nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
3525
3526         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
3527         assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
3528
3529         // Even though the funding transaction is created by `nodes[0]`, the `FundingCreated` msg is
3530         // never sent to `nodes[1]`, and therefore the tx is never signed by either party nor
3531         // broadcasted.
3532         {
3533                 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
3534         }
3535
3536         // Ensure that the channel is closed with `ClosureReason::DisconnectedPeer` when the peers are
3537         // disconnected before the funding transaction was broadcasted.
3538         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3539         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3540
3541         check_closed_event!(nodes[0], 1, ClosureReason::DisconnectedPeer);
3542         check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
3543 }
3544
3545 #[test]
3546 fn test_simple_peer_disconnect() {
3547         // Test that we can reconnect when there are no lost messages
3548         let chanmon_cfgs = create_chanmon_cfgs(3);
3549         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3550         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3551         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3552         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3553         create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3554
3555         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3556         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3557         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3558
3559         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3560         let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3561         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3562         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3563
3564         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3565         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3566         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3567
3568         let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3569         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3570         let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3571         let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3572
3573         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3574         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3575
3576         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3577         fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3578
3579         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3580         {
3581                 let events = nodes[0].node.get_and_clear_pending_events();
3582                 assert_eq!(events.len(), 3);
3583                 match events[0] {
3584                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3585                                 assert_eq!(payment_preimage, payment_preimage_3);
3586                                 assert_eq!(payment_hash, payment_hash_3);
3587                         },
3588                         _ => panic!("Unexpected event"),
3589                 }
3590                 match events[1] {
3591                         Event::PaymentPathFailed { payment_hash, payment_failed_permanently, .. } => {
3592                                 assert_eq!(payment_hash, payment_hash_5);
3593                                 assert!(payment_failed_permanently);
3594                         },
3595                         _ => panic!("Unexpected event"),
3596                 }
3597                 match events[2] {
3598                         Event::PaymentPathSuccessful { .. } => {},
3599                         _ => panic!("Unexpected event"),
3600                 }
3601         }
3602
3603         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3604         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3605 }
3606
3607 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3608         // Test that we can reconnect when in-flight HTLC updates get dropped
3609         let chanmon_cfgs = create_chanmon_cfgs(2);
3610         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3611         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3612         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3613
3614         let mut as_channel_ready = None;
3615         if messages_delivered == 0 {
3616                 let (channel_ready, _, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3617                 as_channel_ready = Some(channel_ready);
3618                 // nodes[1] doesn't receive the channel_ready message (it'll be re-sent on reconnect)
3619                 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3620                 // it before the channel_reestablish message.
3621         } else {
3622                 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
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::PaymentReceived { ref payment_hash, ref purpose, amount_msat } => {
3727                         assert_eq!(payment_hash_1, *payment_hash);
3728                         assert_eq!(amount_msat, 1_000_000);
3729                         match &purpose {
3730                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3731                                         assert!(payment_preimage.is_none());
3732                                         assert_eq!(payment_secret_1, *payment_secret);
3733                                 },
3734                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
3735                         }
3736                 },
3737                 _ => panic!("Unexpected event"),
3738         }
3739
3740         nodes[1].node.claim_funds(payment_preimage_1);
3741         check_added_monitors!(nodes[1], 1);
3742         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3743
3744         let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3745         assert_eq!(events_3.len(), 1);
3746         let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3747                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3748                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3749                         assert!(updates.update_add_htlcs.is_empty());
3750                         assert!(updates.update_fail_htlcs.is_empty());
3751                         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3752                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3753                         assert!(updates.update_fee.is_none());
3754                         (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3755                 },
3756                 _ => panic!("Unexpected event"),
3757         };
3758
3759         if messages_delivered >= 1 {
3760                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3761
3762                 let events_4 = nodes[0].node.get_and_clear_pending_events();
3763                 assert_eq!(events_4.len(), 1);
3764                 match events_4[0] {
3765                         Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3766                                 assert_eq!(payment_preimage_1, *payment_preimage);
3767                                 assert_eq!(payment_hash_1, *payment_hash);
3768                         },
3769                         _ => panic!("Unexpected event"),
3770                 }
3771
3772                 if messages_delivered >= 2 {
3773                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3774                         check_added_monitors!(nodes[0], 1);
3775                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3776
3777                         if messages_delivered >= 3 {
3778                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3779                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3780                                 check_added_monitors!(nodes[1], 1);
3781
3782                                 if messages_delivered >= 4 {
3783                                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3784                                         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3785                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3786                                         check_added_monitors!(nodes[1], 1);
3787
3788                                         if messages_delivered >= 5 {
3789                                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3790                                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3791                                                 check_added_monitors!(nodes[0], 1);
3792                                         }
3793                                 }
3794                         }
3795                 }
3796         }
3797
3798         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3799         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3800         if messages_delivered < 2 {
3801                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3802                 if messages_delivered < 1 {
3803                         expect_payment_sent!(nodes[0], payment_preimage_1);
3804                 } else {
3805                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3806                 }
3807         } else if messages_delivered == 2 {
3808                 // nodes[0] still wants its RAA + commitment_signed
3809                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3810         } else if messages_delivered == 3 {
3811                 // nodes[0] still wants its commitment_signed
3812                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3813         } else if messages_delivered == 4 {
3814                 // nodes[1] still wants its final RAA
3815                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3816         } else if messages_delivered == 5 {
3817                 // Everything was delivered...
3818                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3819         }
3820
3821         if messages_delivered == 1 || messages_delivered == 2 {
3822                 expect_payment_path_successful!(nodes[0]);
3823         }
3824
3825         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3826         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3827         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3828
3829         if messages_delivered > 2 {
3830                 expect_payment_path_successful!(nodes[0]);
3831         }
3832
3833         // Channel should still work fine...
3834         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3835         let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3836         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3837 }
3838
3839 #[test]
3840 fn test_drop_messages_peer_disconnect_a() {
3841         do_test_drop_messages_peer_disconnect(0, true);
3842         do_test_drop_messages_peer_disconnect(0, false);
3843         do_test_drop_messages_peer_disconnect(1, false);
3844         do_test_drop_messages_peer_disconnect(2, false);
3845 }
3846
3847 #[test]
3848 fn test_drop_messages_peer_disconnect_b() {
3849         do_test_drop_messages_peer_disconnect(3, false);
3850         do_test_drop_messages_peer_disconnect(4, false);
3851         do_test_drop_messages_peer_disconnect(5, false);
3852         do_test_drop_messages_peer_disconnect(6, false);
3853 }
3854
3855 #[test]
3856 fn test_funding_peer_disconnect() {
3857         // Test that we can lock in our funding tx while disconnected
3858         let chanmon_cfgs = create_chanmon_cfgs(2);
3859         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3860         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3861         let persister: test_utils::TestPersister;
3862         let new_chain_monitor: test_utils::TestChainMonitor;
3863         let nodes_0_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
3864         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3865         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3866
3867         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3868         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3869
3870         confirm_transaction(&nodes[0], &tx);
3871         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3872         assert!(events_1.is_empty());
3873
3874         reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3875
3876         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3877         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3878
3879         confirm_transaction(&nodes[1], &tx);
3880         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3881         assert!(events_2.is_empty());
3882
3883         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
3884         let as_reestablish = get_chan_reestablish_msgs!(nodes[0], nodes[1]).pop().unwrap();
3885         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
3886         let bs_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]).pop().unwrap();
3887
3888         // nodes[0] hasn't yet received a channel_ready, so it only sends that on reconnect.
3889         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
3890         let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3891         assert_eq!(events_3.len(), 1);
3892         let as_channel_ready = match events_3[0] {
3893                 MessageSendEvent::SendChannelReady { ref node_id, ref msg } => {
3894                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3895                         msg.clone()
3896                 },
3897                 _ => panic!("Unexpected event {:?}", events_3[0]),
3898         };
3899
3900         // nodes[1] received nodes[0]'s channel_ready on the first reconnect above, so it should send
3901         // announcement_signatures as well as channel_update.
3902         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reestablish);
3903         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3904         assert_eq!(events_4.len(), 3);
3905         let chan_id;
3906         let bs_channel_ready = match events_4[0] {
3907                 MessageSendEvent::SendChannelReady { ref node_id, ref msg } => {
3908                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3909                         chan_id = msg.channel_id;
3910                         msg.clone()
3911                 },
3912                 _ => panic!("Unexpected event {:?}", events_4[0]),
3913         };
3914         let bs_announcement_sigs = match events_4[1] {
3915                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3916                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3917                         msg.clone()
3918                 },
3919                 _ => panic!("Unexpected event {:?}", events_4[1]),
3920         };
3921         match events_4[2] {
3922                 MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } => {
3923                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3924                 },
3925                 _ => panic!("Unexpected event {:?}", events_4[2]),
3926         }
3927
3928         // Re-deliver nodes[0]'s channel_ready, which nodes[1] can safely ignore. It currently
3929         // generates a duplicative private channel_update
3930         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
3931         let events_5 = nodes[1].node.get_and_clear_pending_msg_events();
3932         assert_eq!(events_5.len(), 1);
3933         match events_5[0] {
3934                 MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } => {
3935                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3936                 },
3937                 _ => panic!("Unexpected event {:?}", events_5[0]),
3938         };
3939
3940         // When we deliver nodes[1]'s channel_ready, however, nodes[0] will generate its
3941         // announcement_signatures.
3942         nodes[0].node.handle_channel_ready(&nodes[1].node.get_our_node_id(), &bs_channel_ready);
3943         let events_6 = nodes[0].node.get_and_clear_pending_msg_events();
3944         assert_eq!(events_6.len(), 1);
3945         let as_announcement_sigs = match events_6[0] {
3946                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3947                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3948                         msg.clone()
3949                 },
3950                 _ => panic!("Unexpected event {:?}", events_6[0]),
3951         };
3952         expect_channel_ready_event(&nodes[0], &nodes[1].node.get_our_node_id());
3953         expect_channel_ready_event(&nodes[1], &nodes[0].node.get_our_node_id());
3954
3955         // When we deliver nodes[1]'s announcement_signatures to nodes[0], nodes[0] should immediately
3956         // broadcast the channel announcement globally, as well as re-send its (now-public)
3957         // channel_update.
3958         nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3959         let events_7 = nodes[0].node.get_and_clear_pending_msg_events();
3960         assert_eq!(events_7.len(), 1);
3961         let (chan_announcement, as_update) = match events_7[0] {
3962                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3963                         (msg.clone(), update_msg.clone())
3964                 },
3965                 _ => panic!("Unexpected event {:?}", events_7[0]),
3966         };
3967
3968         // Finally, deliver nodes[0]'s announcement_signatures to nodes[1] and make sure it creates the
3969         // same channel_announcement.
3970         nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3971         let events_8 = nodes[1].node.get_and_clear_pending_msg_events();
3972         assert_eq!(events_8.len(), 1);
3973         let bs_update = match events_8[0] {
3974                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3975                         assert_eq!(*msg, chan_announcement);
3976                         update_msg.clone()
3977                 },
3978                 _ => panic!("Unexpected event {:?}", events_8[0]),
3979         };
3980
3981         // Provide the channel announcement and public updates to the network graph
3982         nodes[0].gossip_sync.handle_channel_announcement(&chan_announcement).unwrap();
3983         nodes[0].gossip_sync.handle_channel_update(&bs_update).unwrap();
3984         nodes[0].gossip_sync.handle_channel_update(&as_update).unwrap();
3985
3986         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3987         let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3988         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
3989
3990         // Check that after deserialization and reconnection we can still generate an identical
3991         // channel_announcement from the cached signatures.
3992         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3993
3994         let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
3995
3996         reload_node!(nodes[0], &nodes[0].node.encode(), &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_0_deserialized);
3997
3998         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3999 }
4000
4001 #[test]
4002 fn test_channel_ready_without_best_block_updated() {
4003         // Previously, if we were offline when a funding transaction was locked in, and then we came
4004         // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
4005         // generate a channel_ready until a later best_block_updated. This tests that we generate the
4006         // channel_ready immediately instead.
4007         let chanmon_cfgs = create_chanmon_cfgs(2);
4008         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4009         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4010         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4011         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
4012
4013         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());
4014
4015         let conf_height = nodes[0].best_block_info().1 + 1;
4016         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
4017         let block_txn = [funding_tx];
4018         let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
4019         let conf_block_header = nodes[0].get_block_header(conf_height);
4020         nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
4021
4022         // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
4023         let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
4024         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
4025 }
4026
4027 #[test]
4028 fn test_drop_messages_peer_disconnect_dual_htlc() {
4029         // Test that we can handle reconnecting when both sides of a channel have pending
4030         // commitment_updates when we disconnect.
4031         let chanmon_cfgs = create_chanmon_cfgs(2);
4032         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4033         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4034         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4035         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4036
4037         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
4038
4039         // Now try to send a second payment which will fail to send
4040         let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
4041         nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
4042         check_added_monitors!(nodes[0], 1);
4043
4044         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
4045         assert_eq!(events_1.len(), 1);
4046         match events_1[0] {
4047                 MessageSendEvent::UpdateHTLCs { .. } => {},
4048                 _ => panic!("Unexpected event"),
4049         }
4050
4051         nodes[1].node.claim_funds(payment_preimage_1);
4052         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
4053         check_added_monitors!(nodes[1], 1);
4054
4055         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
4056         assert_eq!(events_2.len(), 1);
4057         match events_2[0] {
4058                 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 } } => {
4059                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
4060                         assert!(update_add_htlcs.is_empty());
4061                         assert_eq!(update_fulfill_htlcs.len(), 1);
4062                         assert!(update_fail_htlcs.is_empty());
4063                         assert!(update_fail_malformed_htlcs.is_empty());
4064                         assert!(update_fee.is_none());
4065
4066                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
4067                         let events_3 = nodes[0].node.get_and_clear_pending_events();
4068                         assert_eq!(events_3.len(), 1);
4069                         match events_3[0] {
4070                                 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4071                                         assert_eq!(*payment_preimage, payment_preimage_1);
4072                                         assert_eq!(*payment_hash, payment_hash_1);
4073                                 },
4074                                 _ => panic!("Unexpected event"),
4075                         }
4076
4077                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
4078                         let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4079                         // No commitment_signed so get_event_msg's assert(len == 1) passes
4080                         check_added_monitors!(nodes[0], 1);
4081                 },
4082                 _ => panic!("Unexpected event"),
4083         }
4084
4085         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
4086         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4087
4088         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
4089         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4090         assert_eq!(reestablish_1.len(), 1);
4091         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
4092         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4093         assert_eq!(reestablish_2.len(), 1);
4094
4095         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4096         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4097         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4098         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4099
4100         assert!(as_resp.0.is_none());
4101         assert!(bs_resp.0.is_none());
4102
4103         assert!(bs_resp.1.is_none());
4104         assert!(bs_resp.2.is_none());
4105
4106         assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4107
4108         assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4109         assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4110         assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4111         assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4112         assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4113         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4114         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4115         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4116         // No commitment_signed so get_event_msg's assert(len == 1) passes
4117         check_added_monitors!(nodes[1], 1);
4118
4119         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4120         let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4121         assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4122         assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4123         assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4124         assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4125         assert!(bs_second_commitment_signed.update_fee.is_none());
4126         check_added_monitors!(nodes[1], 1);
4127
4128         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4129         let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4130         assert!(as_commitment_signed.update_add_htlcs.is_empty());
4131         assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4132         assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4133         assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4134         assert!(as_commitment_signed.update_fee.is_none());
4135         check_added_monitors!(nodes[0], 1);
4136
4137         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4138         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4139         // No commitment_signed so get_event_msg's assert(len == 1) passes
4140         check_added_monitors!(nodes[0], 1);
4141
4142         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4143         let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4144         // No commitment_signed so get_event_msg's assert(len == 1) passes
4145         check_added_monitors!(nodes[1], 1);
4146
4147         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4148         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4149         check_added_monitors!(nodes[1], 1);
4150
4151         expect_pending_htlcs_forwardable!(nodes[1]);
4152
4153         let events_5 = nodes[1].node.get_and_clear_pending_events();
4154         assert_eq!(events_5.len(), 1);
4155         match events_5[0] {
4156                 Event::PaymentReceived { ref payment_hash, ref purpose, .. } => {
4157                         assert_eq!(payment_hash_2, *payment_hash);
4158                         match &purpose {
4159                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4160                                         assert!(payment_preimage.is_none());
4161                                         assert_eq!(payment_secret_2, *payment_secret);
4162                                 },
4163                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
4164                         }
4165                 },
4166                 _ => panic!("Unexpected event"),
4167         }
4168
4169         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4170         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4171         check_added_monitors!(nodes[0], 1);
4172
4173         expect_payment_path_successful!(nodes[0]);
4174         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4175 }
4176
4177 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4178         // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4179         // to avoid our counterparty failing the channel.
4180         let chanmon_cfgs = create_chanmon_cfgs(2);
4181         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4182         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4183         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4184
4185         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4186
4187         let our_payment_hash = if send_partial_mpp {
4188                 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4189                 // Use the utility function send_payment_along_path to send the payment with MPP data which
4190                 // indicates there are more HTLCs coming.
4191                 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.
4192                 let payment_id = PaymentId([42; 32]);
4193                 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash, Some(payment_secret), payment_id, &route).unwrap();
4194                 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();
4195                 check_added_monitors!(nodes[0], 1);
4196                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4197                 assert_eq!(events.len(), 1);
4198                 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4199                 // hop should *not* yet generate any PaymentReceived event(s).
4200                 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4201                 our_payment_hash
4202         } else {
4203                 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4204         };
4205
4206         let mut block = Block {
4207                 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
4208                 txdata: vec![],
4209         };
4210         connect_block(&nodes[0], &block);
4211         connect_block(&nodes[1], &block);
4212         let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4213         for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4214                 block.header.prev_blockhash = block.block_hash();
4215                 connect_block(&nodes[0], &block);
4216                 connect_block(&nodes[1], &block);
4217         }
4218
4219         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
4220
4221         check_added_monitors!(nodes[1], 1);
4222         let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4223         assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4224         assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4225         assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4226         assert!(htlc_timeout_updates.update_fee.is_none());
4227
4228         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4229         commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4230         // 100_000 msat as u64, followed by the height at which we failed back above
4231         let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
4232         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(block_count - 1));
4233         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4234 }
4235
4236 #[test]
4237 fn test_htlc_timeout() {
4238         do_test_htlc_timeout(true);
4239         do_test_htlc_timeout(false);
4240 }
4241
4242 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4243         // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4244         let chanmon_cfgs = create_chanmon_cfgs(3);
4245         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4246         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4247         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4248         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4249         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4250
4251         // Make sure all nodes are at the same starting height
4252         connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4253         connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4254         connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4255
4256         // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4257         let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4258         {
4259                 nodes[1].node.send_payment(&route, first_payment_hash, &Some(first_payment_secret), PaymentId(first_payment_hash.0)).unwrap();
4260         }
4261         assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4262         check_added_monitors!(nodes[1], 1);
4263
4264         // Now attempt to route a second payment, which should be placed in the holding cell
4265         let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4266         let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4267         sending_node.node.send_payment(&route, second_payment_hash, &Some(second_payment_secret), PaymentId(second_payment_hash.0)).unwrap();
4268         if forwarded_htlc {
4269                 check_added_monitors!(nodes[0], 1);
4270                 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4271                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4272                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4273                 expect_pending_htlcs_forwardable!(nodes[1]);
4274         }
4275         check_added_monitors!(nodes[1], 0);
4276
4277         connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4278         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4279         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4280         connect_blocks(&nodes[1], 1);
4281
4282         if forwarded_htlc {
4283                 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 }]);
4284                 check_added_monitors!(nodes[1], 1);
4285                 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4286                 assert_eq!(fail_commit.len(), 1);
4287                 match fail_commit[0] {
4288                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4289                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4290                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4291                         },
4292                         _ => unreachable!(),
4293                 }
4294                 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4295         } else {
4296                 expect_payment_failed!(nodes[1], second_payment_hash, false);
4297         }
4298 }
4299
4300 #[test]
4301 fn test_holding_cell_htlc_add_timeouts() {
4302         do_test_holding_cell_htlc_add_timeouts(false);
4303         do_test_holding_cell_htlc_add_timeouts(true);
4304 }
4305
4306 #[test]
4307 fn test_no_txn_manager_serialize_deserialize() {
4308         let chanmon_cfgs = create_chanmon_cfgs(2);
4309         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4310         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4311         let persister: test_utils::TestPersister;
4312         let new_chain_monitor: test_utils::TestChainMonitor;
4313         let nodes_0_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4314         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4315
4316         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4317
4318         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4319
4320         let chan_0_monitor_serialized =
4321                 get_monitor!(nodes[0], OutPoint { txid: tx.txid(), index: 0 }.to_channel_id()).encode();
4322         reload_node!(nodes[0], nodes[0].node.encode(), &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_0_deserialized);
4323
4324         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
4325         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4326         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
4327         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4328
4329         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4330         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4331         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4332         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4333
4334         let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4335         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
4336         for node in nodes.iter() {
4337                 assert!(node.gossip_sync.handle_channel_announcement(&announcement).unwrap());
4338                 node.gossip_sync.handle_channel_update(&as_update).unwrap();
4339                 node.gossip_sync.handle_channel_update(&bs_update).unwrap();
4340         }
4341
4342         send_payment(&nodes[0], &[&nodes[1]], 1000000);
4343 }
4344
4345 #[test]
4346 fn test_manager_serialize_deserialize_events() {
4347         // This test makes sure the events field in ChannelManager survives de/serialization
4348         let chanmon_cfgs = create_chanmon_cfgs(2);
4349         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4350         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4351         let persister: test_utils::TestPersister;
4352         let new_chain_monitor: test_utils::TestChainMonitor;
4353         let nodes_0_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4354         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4355
4356         // Start creating a channel, but stop right before broadcasting the funding transaction
4357         let channel_value = 100000;
4358         let push_msat = 10001;
4359         let a_flags = channelmanager::provided_init_features();
4360         let b_flags = channelmanager::provided_init_features();
4361         let node_a = nodes.remove(0);
4362         let node_b = nodes.remove(0);
4363         node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
4364         node_b.node.handle_open_channel(&node_a.node.get_our_node_id(), a_flags, &get_event_msg!(node_a, MessageSendEvent::SendOpenChannel, node_b.node.get_our_node_id()));
4365         node_a.node.handle_accept_channel(&node_b.node.get_our_node_id(), b_flags, &get_event_msg!(node_b, MessageSendEvent::SendAcceptChannel, node_a.node.get_our_node_id()));
4366
4367         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, &node_b.node.get_our_node_id(), channel_value, 42);
4368
4369         node_a.node.funding_transaction_generated(&temporary_channel_id, &node_b.node.get_our_node_id(), tx.clone()).unwrap();
4370         check_added_monitors!(node_a, 0);
4371
4372         node_b.node.handle_funding_created(&node_a.node.get_our_node_id(), &get_event_msg!(node_a, MessageSendEvent::SendFundingCreated, node_b.node.get_our_node_id()));
4373         {
4374                 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
4375                 assert_eq!(added_monitors.len(), 1);
4376                 assert_eq!(added_monitors[0].0, funding_output);
4377                 added_monitors.clear();
4378         }
4379
4380         let bs_funding_signed = get_event_msg!(node_b, MessageSendEvent::SendFundingSigned, node_a.node.get_our_node_id());
4381         node_a.node.handle_funding_signed(&node_b.node.get_our_node_id(), &bs_funding_signed);
4382         {
4383                 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
4384                 assert_eq!(added_monitors.len(), 1);
4385                 assert_eq!(added_monitors[0].0, funding_output);
4386                 added_monitors.clear();
4387         }
4388         // Normally, this is where node_a would broadcast the funding transaction, but the test de/serializes first instead
4389
4390         nodes.push(node_a);
4391         nodes.push(node_b);
4392
4393         // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4394         let chan_0_monitor_serialized = get_monitor!(nodes[0], bs_funding_signed.channel_id).encode();
4395         reload_node!(nodes[0], nodes[0].node.encode(), &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_0_deserialized);
4396
4397         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4398
4399         // After deserializing, make sure the funding_transaction is still held by the channel manager
4400         let events_4 = nodes[0].node.get_and_clear_pending_events();
4401         assert_eq!(events_4.len(), 0);
4402         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
4403         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
4404
4405         // Make sure the channel is functioning as though the de/serialization never happened
4406         assert_eq!(nodes[0].node.list_channels().len(), 1);
4407
4408         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
4409         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4410         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
4411         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4412
4413         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4414         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4415         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4416         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4417
4418         let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4419         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
4420         for node in nodes.iter() {
4421                 assert!(node.gossip_sync.handle_channel_announcement(&announcement).unwrap());
4422                 node.gossip_sync.handle_channel_update(&as_update).unwrap();
4423                 node.gossip_sync.handle_channel_update(&bs_update).unwrap();
4424         }
4425
4426         send_payment(&nodes[0], &[&nodes[1]], 1000000);
4427 }
4428
4429 #[test]
4430 fn test_simple_manager_serialize_deserialize() {
4431         let chanmon_cfgs = create_chanmon_cfgs(2);
4432         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4433         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4434         let persister: test_utils::TestPersister;
4435         let new_chain_monitor: test_utils::TestChainMonitor;
4436         let nodes_0_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4437         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4438         let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
4439
4440         let (our_payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4441         let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4442
4443         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4444
4445         let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
4446         reload_node!(nodes[0], nodes[0].node.encode(), &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_0_deserialized);
4447
4448         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4449
4450         fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4451         claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
4452 }
4453
4454 #[test]
4455 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4456         // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4457         let chanmon_cfgs = create_chanmon_cfgs(4);
4458         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4459         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4460         let logger: test_utils::TestLogger;
4461         let fee_estimator: test_utils::TestFeeEstimator;
4462         let persister: test_utils::TestPersister;
4463         let new_chain_monitor: test_utils::TestChainMonitor;
4464         let nodes_0_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4465         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4466         let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
4467         let chan_id_2 = create_announced_chan_between_nodes(&nodes, 2, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
4468         let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4469
4470         let mut node_0_stale_monitors_serialized = Vec::new();
4471         for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4472                 let mut writer = test_utils::TestVecWriter(Vec::new());
4473                 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4474                 node_0_stale_monitors_serialized.push(writer.0);
4475         }
4476
4477         let (our_payment_preimage, _, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4478
4479         // Serialize the ChannelManager here, but the monitor we keep up-to-date
4480         let nodes_0_serialized = nodes[0].node.encode();
4481
4482         route_payment(&nodes[0], &[&nodes[3]], 1000000);
4483         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4484         nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4485         nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4486
4487         // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4488         // nodes[3])
4489         let mut node_0_monitors_serialized = Vec::new();
4490         for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4491                 node_0_monitors_serialized.push(get_monitor!(nodes[0], chan_id_iter).encode());
4492         }
4493
4494         logger = test_utils::TestLogger::new();
4495         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4496         persister = test_utils::TestPersister::new();
4497         let keys_manager = &chanmon_cfgs[0].keys_manager;
4498         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4499         nodes[0].chain_monitor = &new_chain_monitor;
4500
4501
4502         let mut node_0_stale_monitors = Vec::new();
4503         for serialized in node_0_stale_monitors_serialized.iter() {
4504                 let mut read = &serialized[..];
4505                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4506                 assert!(read.is_empty());
4507                 node_0_stale_monitors.push(monitor);
4508         }
4509
4510         let mut node_0_monitors = Vec::new();
4511         for serialized in node_0_monitors_serialized.iter() {
4512                 let mut read = &serialized[..];
4513                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4514                 assert!(read.is_empty());
4515                 node_0_monitors.push(monitor);
4516         }
4517
4518         let mut nodes_0_read = &nodes_0_serialized[..];
4519         if let Err(msgs::DecodeError::InvalidValue) =
4520                 <(BlockHash, ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4521                 default_config: UserConfig::default(),
4522                 keys_manager,
4523                 fee_estimator: &fee_estimator,
4524                 chain_monitor: nodes[0].chain_monitor,
4525                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4526                 logger: &logger,
4527                 channel_monitors: node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4528         }) { } else {
4529                 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4530         };
4531
4532         let mut nodes_0_read = &nodes_0_serialized[..];
4533         let (_, nodes_0_deserialized_tmp) =
4534                 <(BlockHash, ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4535                 default_config: UserConfig::default(),
4536                 keys_manager,
4537                 fee_estimator: &fee_estimator,
4538                 chain_monitor: nodes[0].chain_monitor,
4539                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4540                 logger: &logger,
4541                 channel_monitors: node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4542         }).unwrap();
4543         nodes_0_deserialized = nodes_0_deserialized_tmp;
4544         assert!(nodes_0_read.is_empty());
4545
4546         { // Channel close should result in a commitment tx
4547                 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4548                 assert_eq!(txn.len(), 1);
4549                 check_spends!(txn[0], funding_tx);
4550                 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4551         }
4552
4553         for monitor in node_0_monitors.drain(..) {
4554                 assert_eq!(nodes[0].chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor),
4555                         ChannelMonitorUpdateStatus::Completed);
4556                 check_added_monitors!(nodes[0], 1);
4557         }
4558         nodes[0].node = &nodes_0_deserialized;
4559         check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
4560
4561         // nodes[1] and nodes[2] have no lost state with nodes[0]...
4562         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4563         reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4564         //... and we can even still claim the payment!
4565         claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage);
4566
4567         nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
4568         let reestablish = get_chan_reestablish_msgs!(nodes[3], nodes[0]).pop().unwrap();
4569         nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
4570         nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4571         let mut found_err = false;
4572         for msg_event in nodes[0].node.get_and_clear_pending_msg_events() {
4573                 if let MessageSendEvent::HandleError { ref action, .. } = msg_event {
4574                         match action {
4575                                 &ErrorAction::SendErrorMessage { ref msg } => {
4576                                         assert_eq!(msg.channel_id, channel_id);
4577                                         assert!(!found_err);
4578                                         found_err = true;
4579                                 },
4580                                 _ => panic!("Unexpected event!"),
4581                         }
4582                 }
4583         }
4584         assert!(found_err);
4585 }
4586
4587 macro_rules! check_spendable_outputs {
4588         ($node: expr, $keysinterface: expr) => {
4589                 {
4590                         let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4591                         let mut txn = Vec::new();
4592                         let mut all_outputs = Vec::new();
4593                         let secp_ctx = Secp256k1::new();
4594                         for event in events.drain(..) {
4595                                 match event {
4596                                         Event::SpendableOutputs { mut outputs } => {
4597                                                 for outp in outputs.drain(..) {
4598                                                         txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4599                                                         all_outputs.push(outp);
4600                                                 }
4601                                         },
4602                                         _ => panic!("Unexpected event"),
4603                                 };
4604                         }
4605                         if all_outputs.len() > 1 {
4606                                 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) {
4607                                         txn.push(tx);
4608                                 }
4609                         }
4610                         txn
4611                 }
4612         }
4613 }
4614
4615 #[test]
4616 fn test_claim_sizeable_push_msat() {
4617         // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4618         let chanmon_cfgs = create_chanmon_cfgs(2);
4619         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4620         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4621         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4622
4623         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());
4624         nodes[1].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
4625         check_closed_broadcast!(nodes[1], true);
4626         check_added_monitors!(nodes[1], 1);
4627         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4628         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4629         assert_eq!(node_txn.len(), 1);
4630         check_spends!(node_txn[0], chan.3);
4631         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
4632
4633         mine_transaction(&nodes[1], &node_txn[0]);
4634         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4635
4636         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4637         assert_eq!(spend_txn.len(), 1);
4638         assert_eq!(spend_txn[0].input.len(), 1);
4639         check_spends!(spend_txn[0], node_txn[0]);
4640         assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4641 }
4642
4643 #[test]
4644 fn test_claim_on_remote_sizeable_push_msat() {
4645         // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4646         // to_remote output is encumbered by a P2WPKH
4647         let chanmon_cfgs = create_chanmon_cfgs(2);
4648         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4649         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4650         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4651
4652         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());
4653         nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
4654         check_closed_broadcast!(nodes[0], true);
4655         check_added_monitors!(nodes[0], 1);
4656         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4657
4658         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4659         assert_eq!(node_txn.len(), 1);
4660         check_spends!(node_txn[0], chan.3);
4661         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
4662
4663         mine_transaction(&nodes[1], &node_txn[0]);
4664         check_closed_broadcast!(nodes[1], true);
4665         check_added_monitors!(nodes[1], 1);
4666         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4667         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4668
4669         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4670         assert_eq!(spend_txn.len(), 1);
4671         check_spends!(spend_txn[0], node_txn[0]);
4672 }
4673
4674 #[test]
4675 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4676         // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4677         // to_remote output is encumbered by a P2WPKH
4678
4679         let chanmon_cfgs = create_chanmon_cfgs(2);
4680         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4681         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4682         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4683
4684         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4685         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4686         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4687         assert_eq!(revoked_local_txn[0].input.len(), 1);
4688         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4689
4690         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4691         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4692         check_closed_broadcast!(nodes[1], true);
4693         check_added_monitors!(nodes[1], 1);
4694         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4695
4696         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4697         mine_transaction(&nodes[1], &node_txn[0]);
4698         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4699
4700         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4701         assert_eq!(spend_txn.len(), 3);
4702         check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4703         check_spends!(spend_txn[1], node_txn[0]);
4704         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4705 }
4706
4707 #[test]
4708 fn test_static_spendable_outputs_preimage_tx() {
4709         let chanmon_cfgs = create_chanmon_cfgs(2);
4710         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4711         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4712         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4713
4714         // Create some initial channels
4715         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4716
4717         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
4718
4719         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4720         assert_eq!(commitment_tx[0].input.len(), 1);
4721         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4722
4723         // Settle A's commitment tx on B's chain
4724         nodes[1].node.claim_funds(payment_preimage);
4725         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
4726         check_added_monitors!(nodes[1], 1);
4727         mine_transaction(&nodes[1], &commitment_tx[0]);
4728         check_added_monitors!(nodes[1], 1);
4729         let events = nodes[1].node.get_and_clear_pending_msg_events();
4730         match events[0] {
4731                 MessageSendEvent::UpdateHTLCs { .. } => {},
4732                 _ => panic!("Unexpected event"),
4733         }
4734         match events[1] {
4735                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4736                 _ => panic!("Unexepected event"),
4737         }
4738
4739         // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4740         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4741         assert_eq!(node_txn.len(), 3);
4742         check_spends!(node_txn[0], commitment_tx[0]);
4743         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4744         check_spends!(node_txn[1], chan_1.3);
4745         check_spends!(node_txn[2], node_txn[1]);
4746
4747         mine_transaction(&nodes[1], &node_txn[0]);
4748         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4749         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4750
4751         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4752         assert_eq!(spend_txn.len(), 1);
4753         check_spends!(spend_txn[0], node_txn[0]);
4754 }
4755
4756 #[test]
4757 fn test_static_spendable_outputs_timeout_tx() {
4758         let chanmon_cfgs = create_chanmon_cfgs(2);
4759         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4760         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4761         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4762
4763         // Create some initial channels
4764         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4765
4766         // Rebalance the network a bit by relaying one payment through all the channels ...
4767         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4768
4769         let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4770
4771         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4772         assert_eq!(commitment_tx[0].input.len(), 1);
4773         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4774
4775         // Settle A's commitment tx on B' chain
4776         mine_transaction(&nodes[1], &commitment_tx[0]);
4777         check_added_monitors!(nodes[1], 1);
4778         let events = nodes[1].node.get_and_clear_pending_msg_events();
4779         match events[0] {
4780                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4781                 _ => panic!("Unexpected event"),
4782         }
4783         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4784
4785         // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4786         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4787         assert_eq!(node_txn.len(), 2); // ChannelManager : 1 local commitent tx, ChannelMonitor: timeout tx
4788         check_spends!(node_txn[0], chan_1.3.clone());
4789         check_spends!(node_txn[1],  commitment_tx[0].clone());
4790         assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4791
4792         mine_transaction(&nodes[1], &node_txn[1]);
4793         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4794         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4795         expect_payment_failed!(nodes[1], our_payment_hash, false);
4796
4797         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4798         assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4799         check_spends!(spend_txn[0], commitment_tx[0]);
4800         check_spends!(spend_txn[1], node_txn[1]);
4801         check_spends!(spend_txn[2], node_txn[1], commitment_tx[0]); // All outputs
4802 }
4803
4804 #[test]
4805 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4806         let chanmon_cfgs = create_chanmon_cfgs(2);
4807         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4808         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4809         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4810
4811         // Create some initial channels
4812         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4813
4814         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4815         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4816         assert_eq!(revoked_local_txn[0].input.len(), 1);
4817         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4818
4819         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4820
4821         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4822         check_closed_broadcast!(nodes[1], true);
4823         check_added_monitors!(nodes[1], 1);
4824         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4825
4826         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4827         assert_eq!(node_txn.len(), 2);
4828         assert_eq!(node_txn[0].input.len(), 2);
4829         check_spends!(node_txn[0], revoked_local_txn[0]);
4830
4831         mine_transaction(&nodes[1], &node_txn[0]);
4832         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4833
4834         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4835         assert_eq!(spend_txn.len(), 1);
4836         check_spends!(spend_txn[0], node_txn[0]);
4837 }
4838
4839 #[test]
4840 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4841         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4842         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4843         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4844         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4845         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4846
4847         // Create some initial channels
4848         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4849
4850         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4851         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4852         assert_eq!(revoked_local_txn[0].input.len(), 1);
4853         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4854
4855         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4856
4857         // A will generate HTLC-Timeout from revoked commitment tx
4858         mine_transaction(&nodes[0], &revoked_local_txn[0]);
4859         check_closed_broadcast!(nodes[0], true);
4860         check_added_monitors!(nodes[0], 1);
4861         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4862         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4863
4864         let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4865         assert_eq!(revoked_htlc_txn.len(), 2);
4866         check_spends!(revoked_htlc_txn[0], chan_1.3);
4867         assert_eq!(revoked_htlc_txn[1].input.len(), 1);
4868         assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4869         check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
4870         assert_ne!(revoked_htlc_txn[1].lock_time.0, 0); // HTLC-Timeout
4871
4872         // B will generate justice tx from A's revoked commitment/HTLC tx
4873         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
4874         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[1].clone()] });
4875         check_closed_broadcast!(nodes[1], true);
4876         check_added_monitors!(nodes[1], 1);
4877         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4878
4879         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4880         assert_eq!(node_txn.len(), 3); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs, ChannelManager: local commitment tx
4881         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4882         // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
4883         // transactions next...
4884         assert_eq!(node_txn[0].input.len(), 3);
4885         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[1]);
4886
4887         assert_eq!(node_txn[1].input.len(), 2);
4888         check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[1]);
4889         if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[1].txid() {
4890                 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
4891         } else {
4892                 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[1].txid());
4893                 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[1].input[0].previous_output);
4894         }
4895
4896         assert_eq!(node_txn[2].input.len(), 1);
4897         check_spends!(node_txn[2], chan_1.3);
4898
4899         mine_transaction(&nodes[1], &node_txn[1]);
4900         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4901
4902         // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4903         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4904         assert_eq!(spend_txn.len(), 1);
4905         assert_eq!(spend_txn[0].input.len(), 1);
4906         check_spends!(spend_txn[0], node_txn[1]);
4907 }
4908
4909 #[test]
4910 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4911         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4912         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4913         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4914         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4915         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4916
4917         // Create some initial channels
4918         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4919
4920         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4921         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4922         assert_eq!(revoked_local_txn[0].input.len(), 1);
4923         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4924
4925         // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4926         assert_eq!(revoked_local_txn[0].output.len(), 2);
4927
4928         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4929
4930         // B will generate HTLC-Success from revoked commitment tx
4931         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4932         check_closed_broadcast!(nodes[1], true);
4933         check_added_monitors!(nodes[1], 1);
4934         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4935         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4936
4937         assert_eq!(revoked_htlc_txn.len(), 2);
4938         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4939         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4940         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4941
4942         // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
4943         let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
4944         assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
4945
4946         // A will generate justice tx from B's revoked commitment/HTLC tx
4947         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
4948         connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
4949         check_closed_broadcast!(nodes[0], true);
4950         check_added_monitors!(nodes[0], 1);
4951         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4952
4953         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4954         assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
4955
4956         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4957         // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4958         // transactions next...
4959         assert_eq!(node_txn[0].input.len(), 2);
4960         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4961         if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4962                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4963         } else {
4964                 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4965                 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4966         }
4967
4968         assert_eq!(node_txn[1].input.len(), 1);
4969         check_spends!(node_txn[1], revoked_htlc_txn[0]);
4970
4971         check_spends!(node_txn[2], chan_1.3);
4972
4973         mine_transaction(&nodes[0], &node_txn[1]);
4974         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
4975
4976         // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
4977         // didn't try to generate any new transactions.
4978
4979         // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4980         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
4981         assert_eq!(spend_txn.len(), 3);
4982         assert_eq!(spend_txn[0].input.len(), 1);
4983         check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
4984         assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4985         check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
4986         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
4987 }
4988
4989 #[test]
4990 fn test_onchain_to_onchain_claim() {
4991         // Test that in case of channel closure, we detect the state of output and claim HTLC
4992         // on downstream peer's remote commitment tx.
4993         // First, have C claim an HTLC against its own latest commitment transaction.
4994         // Then, broadcast these to B, which should update the monitor downstream on the A<->B
4995         // channel.
4996         // Finally, check that B will claim the HTLC output if A's latest commitment transaction
4997         // gets broadcast.
4998
4999         let chanmon_cfgs = create_chanmon_cfgs(3);
5000         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5001         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5002         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5003
5004         // Create some initial channels
5005         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5006         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5007
5008         // Ensure all nodes are at the same height
5009         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5010         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5011         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5012         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5013
5014         // Rebalance the network a bit by relaying one payment through all the channels ...
5015         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5016         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5017
5018         let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
5019         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
5020         check_spends!(commitment_tx[0], chan_2.3);
5021         nodes[2].node.claim_funds(payment_preimage);
5022         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
5023         check_added_monitors!(nodes[2], 1);
5024         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5025         assert!(updates.update_add_htlcs.is_empty());
5026         assert!(updates.update_fail_htlcs.is_empty());
5027         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5028         assert!(updates.update_fail_malformed_htlcs.is_empty());
5029
5030         mine_transaction(&nodes[2], &commitment_tx[0]);
5031         check_closed_broadcast!(nodes[2], true);
5032         check_added_monitors!(nodes[2], 1);
5033         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5034
5035         let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
5036         assert_eq!(c_txn.len(), 3);
5037         assert_eq!(c_txn[0], c_txn[2]);
5038         assert_eq!(commitment_tx[0], c_txn[1]);
5039         check_spends!(c_txn[1], chan_2.3);
5040         check_spends!(c_txn[2], c_txn[1]);
5041         assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
5042         assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5043         assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5044         assert_eq!(c_txn[0].lock_time.0, 0); // Success tx
5045
5046         // 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
5047         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
5048         connect_block(&nodes[1], &Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]});
5049         check_added_monitors!(nodes[1], 1);
5050         let events = nodes[1].node.get_and_clear_pending_events();
5051         assert_eq!(events.len(), 2);
5052         match events[0] {
5053                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5054                 _ => panic!("Unexpected event"),
5055         }
5056         match events[1] {
5057                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
5058                         assert_eq!(fee_earned_msat, Some(1000));
5059                         assert_eq!(prev_channel_id, Some(chan_1.2));
5060                         assert_eq!(claim_from_onchain_tx, true);
5061                         assert_eq!(next_channel_id, Some(chan_2.2));
5062                 },
5063                 _ => panic!("Unexpected event"),
5064         }
5065         {
5066                 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5067                 // ChannelMonitor: claim tx
5068                 assert_eq!(b_txn.len(), 1);
5069                 check_spends!(b_txn[0], chan_2.3); // B local commitment tx, issued by ChannelManager
5070                 b_txn.clear();
5071         }
5072         check_added_monitors!(nodes[1], 1);
5073         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5074         assert_eq!(msg_events.len(), 3);
5075         match msg_events[0] {
5076                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5077                 _ => panic!("Unexpected event"),
5078         }
5079         match msg_events[1] {
5080                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
5081                 _ => panic!("Unexpected event"),
5082         }
5083         match msg_events[2] {
5084                 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, .. } } => {
5085                         assert!(update_add_htlcs.is_empty());
5086                         assert!(update_fail_htlcs.is_empty());
5087                         assert_eq!(update_fulfill_htlcs.len(), 1);
5088                         assert!(update_fail_malformed_htlcs.is_empty());
5089                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5090                 },
5091                 _ => panic!("Unexpected event"),
5092         };
5093         // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
5094         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5095         mine_transaction(&nodes[1], &commitment_tx[0]);
5096         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5097         let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5098         // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
5099         assert_eq!(b_txn.len(), 3);
5100         check_spends!(b_txn[1], chan_1.3);
5101         check_spends!(b_txn[2], b_txn[1]);
5102         check_spends!(b_txn[0], commitment_tx[0]);
5103         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5104         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5105         assert_eq!(b_txn[0].lock_time.0, 0); // Success tx
5106
5107         check_closed_broadcast!(nodes[1], true);
5108         check_added_monitors!(nodes[1], 1);
5109 }
5110
5111 #[test]
5112 fn test_duplicate_payment_hash_one_failure_one_success() {
5113         // Topology : A --> B --> C --> D
5114         // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5115         // Note that because C will refuse to generate two payment secrets for the same payment hash,
5116         // we forward one of the payments onwards to D.
5117         let chanmon_cfgs = create_chanmon_cfgs(4);
5118         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
5119         // When this test was written, the default base fee floated based on the HTLC count.
5120         // It is now fixed, so we simply set the fee to the expected value here.
5121         let mut config = test_default_channel_config();
5122         config.channel_config.forwarding_fee_base_msat = 196;
5123         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
5124                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5125         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
5126
5127         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5128         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5129         create_announced_chan_between_nodes(&nodes, 2, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5130
5131         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5132         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5133         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5134         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5135         connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
5136
5137         let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 900_000);
5138
5139         let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200).unwrap();
5140         // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
5141         // script push size limit so that the below script length checks match
5142         // ACCEPTED_HTLC_SCRIPT_WEIGHT.
5143         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id())
5144                 .with_features(channelmanager::provided_invoice_features());
5145         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 900000, TEST_FINAL_CLTV - 40);
5146         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 900000, duplicate_payment_hash, payment_secret);
5147
5148         let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5149         assert_eq!(commitment_txn[0].input.len(), 1);
5150         check_spends!(commitment_txn[0], chan_2.3);
5151
5152         mine_transaction(&nodes[1], &commitment_txn[0]);
5153         check_closed_broadcast!(nodes[1], true);
5154         check_added_monitors!(nodes[1], 1);
5155         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5156         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
5157
5158         let htlc_timeout_tx;
5159         { // Extract one of the two HTLC-Timeout transaction
5160                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5161                 // ChannelMonitor: timeout tx * 2-or-3, ChannelManager: local commitment tx
5162                 assert!(node_txn.len() == 4 || node_txn.len() == 3);
5163                 check_spends!(node_txn[0], chan_2.3);
5164
5165                 check_spends!(node_txn[1], commitment_txn[0]);
5166                 assert_eq!(node_txn[1].input.len(), 1);
5167
5168                 if node_txn.len() > 3 {
5169                         check_spends!(node_txn[2], commitment_txn[0]);
5170                         assert_eq!(node_txn[2].input.len(), 1);
5171                         assert_eq!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
5172
5173                         check_spends!(node_txn[3], commitment_txn[0]);
5174                         assert_ne!(node_txn[1].input[0].previous_output, node_txn[3].input[0].previous_output);
5175                 } else {
5176                         check_spends!(node_txn[2], commitment_txn[0]);
5177                         assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
5178                 }
5179
5180                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5181                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5182                 if node_txn.len() > 3 {
5183                         assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5184                 }
5185                 htlc_timeout_tx = node_txn[1].clone();
5186         }
5187
5188         nodes[2].node.claim_funds(our_payment_preimage);
5189         expect_payment_claimed!(nodes[2], duplicate_payment_hash, 900_000);
5190
5191         mine_transaction(&nodes[2], &commitment_txn[0]);
5192         check_added_monitors!(nodes[2], 2);
5193         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5194         let events = nodes[2].node.get_and_clear_pending_msg_events();
5195         match events[0] {
5196                 MessageSendEvent::UpdateHTLCs { .. } => {},
5197                 _ => panic!("Unexpected event"),
5198         }
5199         match events[1] {
5200                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5201                 _ => panic!("Unexepected event"),
5202         }
5203         let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5204         assert_eq!(htlc_success_txn.len(), 5); // ChannelMonitor: HTLC-Success txn (*2 due to 2-HTLC outputs), ChannelManager: local commitment tx + HTLC-Success txn (*2 due to 2-HTLC outputs)
5205         check_spends!(htlc_success_txn[0], commitment_txn[0]);
5206         check_spends!(htlc_success_txn[1], commitment_txn[0]);
5207         assert_eq!(htlc_success_txn[0].input.len(), 1);
5208         assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5209         assert_eq!(htlc_success_txn[1].input.len(), 1);
5210         assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5211         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
5212         assert_eq!(htlc_success_txn[2], commitment_txn[0]);
5213         assert_eq!(htlc_success_txn[3], htlc_success_txn[0]);
5214         assert_eq!(htlc_success_txn[4], htlc_success_txn[1]);
5215         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
5216
5217         mine_transaction(&nodes[1], &htlc_timeout_tx);
5218         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5219         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 }]);
5220         let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5221         assert!(htlc_updates.update_add_htlcs.is_empty());
5222         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5223         let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
5224         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5225         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5226         check_added_monitors!(nodes[1], 1);
5227
5228         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5229         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5230         {
5231                 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5232         }
5233         expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
5234
5235         // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5236         // Note that the fee paid is effectively double as the HTLC value (including the nodes[1] fee
5237         // and nodes[2] fee) is rounded down and then claimed in full.
5238         mine_transaction(&nodes[1], &htlc_success_txn[0]);
5239         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196*2), true, true);
5240         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5241         assert!(updates.update_add_htlcs.is_empty());
5242         assert!(updates.update_fail_htlcs.is_empty());
5243         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5244         assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
5245         assert!(updates.update_fail_malformed_htlcs.is_empty());
5246         check_added_monitors!(nodes[1], 1);
5247
5248         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5249         commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5250
5251         let events = nodes[0].node.get_and_clear_pending_events();
5252         match events[0] {
5253                 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
5254                         assert_eq!(*payment_preimage, our_payment_preimage);
5255                         assert_eq!(*payment_hash, duplicate_payment_hash);
5256                 }
5257                 _ => panic!("Unexpected event"),
5258         }
5259 }
5260
5261 #[test]
5262 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5263         let chanmon_cfgs = create_chanmon_cfgs(2);
5264         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5265         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5266         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5267
5268         // Create some initial channels
5269         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5270
5271         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
5272         let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5273         assert_eq!(local_txn.len(), 1);
5274         assert_eq!(local_txn[0].input.len(), 1);
5275         check_spends!(local_txn[0], chan_1.3);
5276
5277         // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5278         nodes[1].node.claim_funds(payment_preimage);
5279         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
5280         check_added_monitors!(nodes[1], 1);
5281
5282         mine_transaction(&nodes[1], &local_txn[0]);
5283         check_added_monitors!(nodes[1], 1);
5284         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5285         let events = nodes[1].node.get_and_clear_pending_msg_events();
5286         match events[0] {
5287                 MessageSendEvent::UpdateHTLCs { .. } => {},
5288                 _ => panic!("Unexpected event"),
5289         }
5290         match events[1] {
5291                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5292                 _ => panic!("Unexepected event"),
5293         }
5294         let node_tx = {
5295                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5296                 assert_eq!(node_txn.len(), 3);
5297                 assert_eq!(node_txn[0], node_txn[2]);
5298                 assert_eq!(node_txn[1], local_txn[0]);
5299                 assert_eq!(node_txn[0].input.len(), 1);
5300                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5301                 check_spends!(node_txn[0], local_txn[0]);
5302                 node_txn[0].clone()
5303         };
5304
5305         mine_transaction(&nodes[1], &node_tx);
5306         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
5307
5308         // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5309         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5310         assert_eq!(spend_txn.len(), 1);
5311         assert_eq!(spend_txn[0].input.len(), 1);
5312         check_spends!(spend_txn[0], node_tx);
5313         assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5314 }
5315
5316 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5317         // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5318         // unrevoked commitment transaction.
5319         // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5320         // a remote RAA before they could be failed backwards (and combinations thereof).
5321         // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5322         // use the same payment hashes.
5323         // Thus, we use a six-node network:
5324         //
5325         // A \         / E
5326         //    - C - D -
5327         // B /         \ F
5328         // And test where C fails back to A/B when D announces its latest commitment transaction
5329         let chanmon_cfgs = create_chanmon_cfgs(6);
5330         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5331         // When this test was written, the default base fee floated based on the HTLC count.
5332         // It is now fixed, so we simply set the fee to the expected value here.
5333         let mut config = test_default_channel_config();
5334         config.channel_config.forwarding_fee_base_msat = 196;
5335         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
5336                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5337         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5338
5339         let _chan_0_2 = create_announced_chan_between_nodes(&nodes, 0, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5340         let _chan_1_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5341         let chan_2_3 = create_announced_chan_between_nodes(&nodes, 2, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5342         let chan_3_4 = create_announced_chan_between_nodes(&nodes, 3, 4, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5343         let chan_3_5  = create_announced_chan_between_nodes(&nodes, 3, 5, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5344
5345         // Rebalance and check output sanity...
5346         send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
5347         send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
5348         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 2);
5349
5350         let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan_2_3.2).unwrap().holder_dust_limit_satoshis;
5351         // 0th HTLC:
5352         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
5353         // 1st HTLC:
5354         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
5355         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5356         // 2nd HTLC:
5357         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
5358         // 3rd HTLC:
5359         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
5360         // 4th HTLC:
5361         let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5362         // 5th HTLC:
5363         let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5364         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5365         // 6th HTLC:
5366         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());
5367         // 7th HTLC:
5368         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());
5369
5370         // 8th HTLC:
5371         let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5372         // 9th HTLC:
5373         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5374         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
5375
5376         // 10th HTLC:
5377         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
5378         // 11th HTLC:
5379         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5380         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());
5381
5382         // Double-check that six of the new HTLC were added
5383         // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5384         // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5385         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2).len(), 1);
5386         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 8);
5387
5388         // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5389         // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5390         nodes[4].node.fail_htlc_backwards(&payment_hash_1);
5391         nodes[4].node.fail_htlc_backwards(&payment_hash_3);
5392         nodes[4].node.fail_htlc_backwards(&payment_hash_5);
5393         nodes[4].node.fail_htlc_backwards(&payment_hash_6);
5394         check_added_monitors!(nodes[4], 0);
5395
5396         let failed_destinations = vec![
5397                 HTLCDestination::FailedPayment { payment_hash: payment_hash_1 },
5398                 HTLCDestination::FailedPayment { payment_hash: payment_hash_3 },
5399                 HTLCDestination::FailedPayment { payment_hash: payment_hash_5 },
5400                 HTLCDestination::FailedPayment { payment_hash: payment_hash_6 },
5401         ];
5402         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[4], failed_destinations);
5403         check_added_monitors!(nodes[4], 1);
5404
5405         let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5406         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5407         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5408         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5409         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5410         commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5411
5412         // Fail 3rd below-dust and 7th above-dust HTLCs
5413         nodes[5].node.fail_htlc_backwards(&payment_hash_2);
5414         nodes[5].node.fail_htlc_backwards(&payment_hash_4);
5415         check_added_monitors!(nodes[5], 0);
5416
5417         let failed_destinations_2 = vec![
5418                 HTLCDestination::FailedPayment { payment_hash: payment_hash_2 },
5419                 HTLCDestination::FailedPayment { payment_hash: payment_hash_4 },
5420         ];
5421         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[5], failed_destinations_2);
5422         check_added_monitors!(nodes[5], 1);
5423
5424         let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5425         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5426         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5427         commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5428
5429         let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5430
5431         // After 4 and 2 removes respectively above in nodes[4] and nodes[5], nodes[3] should receive 6 PaymentForwardedFailed events
5432         let failed_destinations_3 = vec![
5433                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5434                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5435                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5436                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5437                 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5438                 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5439         ];
5440         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations_3);
5441         check_added_monitors!(nodes[3], 1);
5442         let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5443         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5444         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5445         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5446         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5447         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5448         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5449         if deliver_last_raa {
5450                 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5451         } else {
5452                 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5453         }
5454
5455         // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5456         // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5457         // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5458         // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5459         //
5460         // We now broadcast the latest commitment transaction, which *should* result in failures for
5461         // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5462         // the non-broadcast above-dust HTLCs.
5463         //
5464         // Alternatively, we may broadcast the previous commitment transaction, which should only
5465         // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5466         let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5467
5468         if announce_latest {
5469                 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5470         } else {
5471                 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5472         }
5473         let events = nodes[2].node.get_and_clear_pending_events();
5474         let close_event = if deliver_last_raa {
5475                 assert_eq!(events.len(), 2 + 6);
5476                 events.last().clone().unwrap()
5477         } else {
5478                 assert_eq!(events.len(), 1);
5479                 events.last().clone().unwrap()
5480         };
5481         match close_event {
5482                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5483                 _ => panic!("Unexpected event"),
5484         }
5485
5486         connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5487         check_closed_broadcast!(nodes[2], true);
5488         if deliver_last_raa {
5489                 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5490
5491                 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();
5492                 expect_htlc_handling_failed_destinations!(nodes[2].node.get_and_clear_pending_events(), expected_destinations);
5493         } else {
5494                 let expected_destinations: Vec<HTLCDestination> = if announce_latest {
5495                         repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(9).collect()
5496                 } else {
5497                         repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(6).collect()
5498                 };
5499
5500                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], expected_destinations);
5501         }
5502         check_added_monitors!(nodes[2], 3);
5503
5504         let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5505         assert_eq!(cs_msgs.len(), 2);
5506         let mut a_done = false;
5507         for msg in cs_msgs {
5508                 match msg {
5509                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5510                                 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5511                                 // should be failed-backwards here.
5512                                 let target = if *node_id == nodes[0].node.get_our_node_id() {
5513                                         // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5514                                         for htlc in &updates.update_fail_htlcs {
5515                                                 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 });
5516                                         }
5517                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5518                                         assert!(!a_done);
5519                                         a_done = true;
5520                                         &nodes[0]
5521                                 } else {
5522                                         // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5523                                         for htlc in &updates.update_fail_htlcs {
5524                                                 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5525                                         }
5526                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5527                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5528                                         &nodes[1]
5529                                 };
5530                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5531                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5532                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5533                                 if announce_latest {
5534                                         target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5535                                         if *node_id == nodes[0].node.get_our_node_id() {
5536                                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5537                                         }
5538                                 }
5539                                 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5540                         },
5541                         _ => panic!("Unexpected event"),
5542                 }
5543         }
5544
5545         let as_events = nodes[0].node.get_and_clear_pending_events();
5546         assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5547         let mut as_failds = HashSet::new();
5548         let mut as_updates = 0;
5549         for event in as_events.iter() {
5550                 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref network_update, .. } = event {
5551                         assert!(as_failds.insert(*payment_hash));
5552                         if *payment_hash != payment_hash_2 {
5553                                 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5554                         } else {
5555                                 assert!(!payment_failed_permanently);
5556                         }
5557                         if network_update.is_some() {
5558                                 as_updates += 1;
5559                         }
5560                 } else { panic!("Unexpected event"); }
5561         }
5562         assert!(as_failds.contains(&payment_hash_1));
5563         assert!(as_failds.contains(&payment_hash_2));
5564         if announce_latest {
5565                 assert!(as_failds.contains(&payment_hash_3));
5566                 assert!(as_failds.contains(&payment_hash_5));
5567         }
5568         assert!(as_failds.contains(&payment_hash_6));
5569
5570         let bs_events = nodes[1].node.get_and_clear_pending_events();
5571         assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5572         let mut bs_failds = HashSet::new();
5573         let mut bs_updates = 0;
5574         for event in bs_events.iter() {
5575                 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref network_update, .. } = event {
5576                         assert!(bs_failds.insert(*payment_hash));
5577                         if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5578                                 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5579                         } else {
5580                                 assert!(!payment_failed_permanently);
5581                         }
5582                         if network_update.is_some() {
5583                                 bs_updates += 1;
5584                         }
5585                 } else { panic!("Unexpected event"); }
5586         }
5587         assert!(bs_failds.contains(&payment_hash_1));
5588         assert!(bs_failds.contains(&payment_hash_2));
5589         if announce_latest {
5590                 assert!(bs_failds.contains(&payment_hash_4));
5591         }
5592         assert!(bs_failds.contains(&payment_hash_5));
5593
5594         // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5595         // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5596         // unknown-preimage-etc, B should have gotten 2. Thus, in the
5597         // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5598         assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5599         assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5600 }
5601
5602 #[test]
5603 fn test_fail_backwards_latest_remote_announce_a() {
5604         do_test_fail_backwards_unrevoked_remote_announce(false, true);
5605 }
5606
5607 #[test]
5608 fn test_fail_backwards_latest_remote_announce_b() {
5609         do_test_fail_backwards_unrevoked_remote_announce(true, true);
5610 }
5611
5612 #[test]
5613 fn test_fail_backwards_previous_remote_announce() {
5614         do_test_fail_backwards_unrevoked_remote_announce(false, false);
5615         // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5616         // tested for in test_commitment_revoked_fail_backward_exhaustive()
5617 }
5618
5619 #[test]
5620 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5621         let chanmon_cfgs = create_chanmon_cfgs(2);
5622         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5623         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5624         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5625
5626         // Create some initial channels
5627         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5628
5629         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5630         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5631         assert_eq!(local_txn[0].input.len(), 1);
5632         check_spends!(local_txn[0], chan_1.3);
5633
5634         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5635         mine_transaction(&nodes[0], &local_txn[0]);
5636         check_closed_broadcast!(nodes[0], true);
5637         check_added_monitors!(nodes[0], 1);
5638         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5639         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5640
5641         let htlc_timeout = {
5642                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5643                 assert_eq!(node_txn.len(), 2);
5644                 check_spends!(node_txn[0], chan_1.3);
5645                 assert_eq!(node_txn[1].input.len(), 1);
5646                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5647                 check_spends!(node_txn[1], local_txn[0]);
5648                 node_txn[1].clone()
5649         };
5650
5651         mine_transaction(&nodes[0], &htlc_timeout);
5652         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5653         expect_payment_failed!(nodes[0], our_payment_hash, false);
5654
5655         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5656         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5657         assert_eq!(spend_txn.len(), 3);
5658         check_spends!(spend_txn[0], local_txn[0]);
5659         assert_eq!(spend_txn[1].input.len(), 1);
5660         check_spends!(spend_txn[1], htlc_timeout);
5661         assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5662         assert_eq!(spend_txn[2].input.len(), 2);
5663         check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5664         assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5665                 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5666 }
5667
5668 #[test]
5669 fn test_key_derivation_params() {
5670         // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5671         // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5672         // let us re-derive the channel key set to then derive a delayed_payment_key.
5673
5674         let chanmon_cfgs = create_chanmon_cfgs(3);
5675
5676         // We manually create the node configuration to backup the seed.
5677         let seed = [42; 32];
5678         let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5679         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);
5680         let network_graph = NetworkGraph::new(chanmon_cfgs[0].chain_source.genesis_hash, &chanmon_cfgs[0].logger);
5681         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, chain_monitor, keys_manager: &keys_manager, network_graph, node_seed: seed, features: channelmanager::provided_init_features() };
5682         let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5683         node_cfgs.remove(0);
5684         node_cfgs.insert(0, node);
5685
5686         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5687         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5688
5689         // Create some initial channels
5690         // Create a dummy channel to advance index by one and thus test re-derivation correctness
5691         // for node 0
5692         let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5693         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5694         assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5695
5696         // Ensure all nodes are at the same height
5697         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5698         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5699         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5700         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5701
5702         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5703         let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5704         let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5705         assert_eq!(local_txn_1[0].input.len(), 1);
5706         check_spends!(local_txn_1[0], chan_1.3);
5707
5708         // We check funding pubkey are unique
5709         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]));
5710         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]));
5711         if from_0_funding_key_0 == from_1_funding_key_0
5712             || from_0_funding_key_0 == from_1_funding_key_1
5713             || from_0_funding_key_1 == from_1_funding_key_0
5714             || from_0_funding_key_1 == from_1_funding_key_1 {
5715                 panic!("Funding pubkeys aren't unique");
5716         }
5717
5718         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5719         mine_transaction(&nodes[0], &local_txn_1[0]);
5720         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5721         check_closed_broadcast!(nodes[0], true);
5722         check_added_monitors!(nodes[0], 1);
5723         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5724
5725         let htlc_timeout = {
5726                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5727                 assert_eq!(node_txn[1].input.len(), 1);
5728                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5729                 check_spends!(node_txn[1], local_txn_1[0]);
5730                 node_txn[1].clone()
5731         };
5732
5733         mine_transaction(&nodes[0], &htlc_timeout);
5734         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5735         expect_payment_failed!(nodes[0], our_payment_hash, false);
5736
5737         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5738         let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5739         let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5740         assert_eq!(spend_txn.len(), 3);
5741         check_spends!(spend_txn[0], local_txn_1[0]);
5742         assert_eq!(spend_txn[1].input.len(), 1);
5743         check_spends!(spend_txn[1], htlc_timeout);
5744         assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5745         assert_eq!(spend_txn[2].input.len(), 2);
5746         check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5747         assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5748                 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5749 }
5750
5751 #[test]
5752 fn test_static_output_closing_tx() {
5753         let chanmon_cfgs = create_chanmon_cfgs(2);
5754         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5755         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5756         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5757
5758         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5759
5760         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5761         let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5762
5763         mine_transaction(&nodes[0], &closing_tx);
5764         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5765         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5766
5767         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5768         assert_eq!(spend_txn.len(), 1);
5769         check_spends!(spend_txn[0], closing_tx);
5770
5771         mine_transaction(&nodes[1], &closing_tx);
5772         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5773         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5774
5775         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5776         assert_eq!(spend_txn.len(), 1);
5777         check_spends!(spend_txn[0], closing_tx);
5778 }
5779
5780 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5781         let chanmon_cfgs = create_chanmon_cfgs(2);
5782         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5783         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5784         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5785         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5786
5787         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3_000_000 });
5788
5789         // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5790         // present in B's local commitment transaction, but none of A's commitment transactions.
5791         nodes[1].node.claim_funds(payment_preimage);
5792         check_added_monitors!(nodes[1], 1);
5793         expect_payment_claimed!(nodes[1], payment_hash, if use_dust { 50000 } else { 3_000_000 });
5794
5795         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5796         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5797         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
5798
5799         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5800         check_added_monitors!(nodes[0], 1);
5801         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5802         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5803         check_added_monitors!(nodes[1], 1);
5804
5805         let starting_block = nodes[1].best_block_info();
5806         let mut block = Block {
5807                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
5808                 txdata: vec![],
5809         };
5810         for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5811                 connect_block(&nodes[1], &block);
5812                 block.header.prev_blockhash = block.block_hash();
5813         }
5814         test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5815         check_closed_broadcast!(nodes[1], true);
5816         check_added_monitors!(nodes[1], 1);
5817         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5818 }
5819
5820 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5821         let chanmon_cfgs = create_chanmon_cfgs(2);
5822         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5823         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5824         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5825         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5826
5827         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5828         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
5829         check_added_monitors!(nodes[0], 1);
5830
5831         let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5832
5833         // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5834         // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5835         // to "time out" the HTLC.
5836
5837         let starting_block = nodes[1].best_block_info();
5838         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
5839
5840         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5841                 connect_block(&nodes[0], &Block { header, txdata: Vec::new()});
5842                 header.prev_blockhash = header.block_hash();
5843         }
5844         test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5845         check_closed_broadcast!(nodes[0], true);
5846         check_added_monitors!(nodes[0], 1);
5847         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5848 }
5849
5850 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5851         let chanmon_cfgs = create_chanmon_cfgs(3);
5852         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5853         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5854         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5855         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5856
5857         // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5858         // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5859         // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5860         // actually revoked.
5861         let htlc_value = if use_dust { 50000 } else { 3000000 };
5862         let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5863         nodes[1].node.fail_htlc_backwards(&our_payment_hash);
5864         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
5865         check_added_monitors!(nodes[1], 1);
5866
5867         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5868         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5869         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5870         check_added_monitors!(nodes[0], 1);
5871         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5872         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5873         check_added_monitors!(nodes[1], 1);
5874         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5875         check_added_monitors!(nodes[1], 1);
5876         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5877
5878         if check_revoke_no_close {
5879                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5880                 check_added_monitors!(nodes[0], 1);
5881         }
5882
5883         let starting_block = nodes[1].best_block_info();
5884         let mut block = Block {
5885                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
5886                 txdata: vec![],
5887         };
5888         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5889                 connect_block(&nodes[0], &block);
5890                 block.header.prev_blockhash = block.block_hash();
5891         }
5892         if !check_revoke_no_close {
5893                 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5894                 check_closed_broadcast!(nodes[0], true);
5895                 check_added_monitors!(nodes[0], 1);
5896                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5897         } else {
5898                 expect_payment_failed!(nodes[0], our_payment_hash, true);
5899         }
5900 }
5901
5902 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5903 // There are only a few cases to test here:
5904 //  * its not really normative behavior, but we test that below-dust HTLCs "included" in
5905 //    broadcastable commitment transactions result in channel closure,
5906 //  * its included in an unrevoked-but-previous remote commitment transaction,
5907 //  * its included in the latest remote or local commitment transactions.
5908 // We test each of the three possible commitment transactions individually and use both dust and
5909 // non-dust HTLCs.
5910 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5911 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5912 // tested for at least one of the cases in other tests.
5913 #[test]
5914 fn htlc_claim_single_commitment_only_a() {
5915         do_htlc_claim_local_commitment_only(true);
5916         do_htlc_claim_local_commitment_only(false);
5917
5918         do_htlc_claim_current_remote_commitment_only(true);
5919         do_htlc_claim_current_remote_commitment_only(false);
5920 }
5921
5922 #[test]
5923 fn htlc_claim_single_commitment_only_b() {
5924         do_htlc_claim_previous_remote_commitment_only(true, false);
5925         do_htlc_claim_previous_remote_commitment_only(false, false);
5926         do_htlc_claim_previous_remote_commitment_only(true, true);
5927         do_htlc_claim_previous_remote_commitment_only(false, true);
5928 }
5929
5930 #[test]
5931 #[should_panic]
5932 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5933         let chanmon_cfgs = create_chanmon_cfgs(2);
5934         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5935         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5936         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5937         // Force duplicate randomness for every get-random call
5938         for node in nodes.iter() {
5939                 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
5940         }
5941
5942         // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5943         let channel_value_satoshis=10000;
5944         let push_msat=10001;
5945         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5946         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5947         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &node0_to_1_send_open_channel);
5948         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
5949
5950         // Create a second channel with the same random values. This used to panic due to a colliding
5951         // channel_id, but now panics due to a colliding outbound SCID alias.
5952         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5953 }
5954
5955 #[test]
5956 fn bolt2_open_channel_sending_node_checks_part2() {
5957         let chanmon_cfgs = create_chanmon_cfgs(2);
5958         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5959         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5960         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5961
5962         // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5963         let channel_value_satoshis=2^24;
5964         let push_msat=10001;
5965         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5966
5967         // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5968         let channel_value_satoshis=10000;
5969         // Test when push_msat is equal to 1000 * funding_satoshis.
5970         let push_msat=1000*channel_value_satoshis+1;
5971         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5972
5973         // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5974         let channel_value_satoshis=10000;
5975         let push_msat=10001;
5976         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
5977         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5978         assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5979
5980         // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5981         // 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
5982         assert!(node0_to_1_send_open_channel.channel_flags<=1);
5983
5984         // 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.
5985         assert!(BREAKDOWN_TIMEOUT>0);
5986         assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5987
5988         // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5989         let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5990         assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5991
5992         // 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.
5993         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5994         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5995         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5996         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5997         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5998 }
5999
6000 #[test]
6001 fn bolt2_open_channel_sane_dust_limit() {
6002         let chanmon_cfgs = create_chanmon_cfgs(2);
6003         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6004         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6005         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6006
6007         let channel_value_satoshis=1000000;
6008         let push_msat=10001;
6009         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
6010         let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6011         node0_to_1_send_open_channel.dust_limit_satoshis = 547;
6012         node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
6013
6014         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &node0_to_1_send_open_channel);
6015         let events = nodes[1].node.get_and_clear_pending_msg_events();
6016         let err_msg = match events[0] {
6017                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
6018                         msg.clone()
6019                 },
6020                 _ => panic!("Unexpected event"),
6021         };
6022         assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
6023 }
6024
6025 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
6026 // originated from our node, its failure is surfaced to the user. We trigger this failure to
6027 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
6028 // is no longer affordable once it's freed.
6029 #[test]
6030 fn test_fail_holding_cell_htlc_upon_free() {
6031         let chanmon_cfgs = create_chanmon_cfgs(2);
6032         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6033         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6034         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6035         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6036
6037         // First nodes[0] generates an update_fee, setting the channel's
6038         // pending_update_fee.
6039         {
6040                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6041                 *feerate_lock += 20;
6042         }
6043         nodes[0].node.timer_tick_occurred();
6044         check_added_monitors!(nodes[0], 1);
6045
6046         let events = nodes[0].node.get_and_clear_pending_msg_events();
6047         assert_eq!(events.len(), 1);
6048         let (update_msg, commitment_signed) = match events[0] {
6049                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6050                         (update_fee.as_ref(), commitment_signed)
6051                 },
6052                 _ => panic!("Unexpected event"),
6053         };
6054
6055         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6056
6057         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6058         let channel_reserve = chan_stat.channel_reserve_msat;
6059         let feerate = get_feerate!(nodes[0], chan.2);
6060         let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6061
6062         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6063         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6064         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6065
6066         // Send a payment which passes reserve checks but gets stuck in the holding cell.
6067         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6068         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6069         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6070
6071         // Flush the pending fee update.
6072         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6073         let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6074         check_added_monitors!(nodes[1], 1);
6075         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
6076         check_added_monitors!(nodes[0], 1);
6077
6078         // Upon receipt of the RAA, there will be an attempt to resend the holding cell
6079         // HTLC, but now that the fee has been raised the payment will now fail, causing
6080         // us to surface its failure to the user.
6081         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6082         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6083         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);
6084         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 {}",
6085                 hex::encode(our_payment_hash.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6086         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6087
6088         // Check that the payment failed to be sent out.
6089         let events = nodes[0].node.get_and_clear_pending_events();
6090         assert_eq!(events.len(), 1);
6091         match &events[0] {
6092                 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, ref network_update, ref all_paths_failed, ref short_channel_id, .. } => {
6093                         assert_eq!(PaymentId(our_payment_hash.0), *payment_id.as_ref().unwrap());
6094                         assert_eq!(our_payment_hash.clone(), *payment_hash);
6095                         assert_eq!(*payment_failed_permanently, false);
6096                         assert_eq!(*all_paths_failed, true);
6097                         assert_eq!(*network_update, None);
6098                         assert_eq!(*short_channel_id, Some(route.paths[0][0].short_channel_id));
6099                 },
6100                 _ => panic!("Unexpected event"),
6101         }
6102 }
6103
6104 // Test that if multiple HTLCs are released from the holding cell and one is
6105 // valid but the other is no longer valid upon release, the valid HTLC can be
6106 // successfully completed while the other one fails as expected.
6107 #[test]
6108 fn test_free_and_fail_holding_cell_htlcs() {
6109         let chanmon_cfgs = create_chanmon_cfgs(2);
6110         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6111         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6112         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6113         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6114
6115         // First nodes[0] generates an update_fee, setting the channel's
6116         // pending_update_fee.
6117         {
6118                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6119                 *feerate_lock += 200;
6120         }
6121         nodes[0].node.timer_tick_occurred();
6122         check_added_monitors!(nodes[0], 1);
6123
6124         let events = nodes[0].node.get_and_clear_pending_msg_events();
6125         assert_eq!(events.len(), 1);
6126         let (update_msg, commitment_signed) = match events[0] {
6127                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6128                         (update_fee.as_ref(), commitment_signed)
6129                 },
6130                 _ => panic!("Unexpected event"),
6131         };
6132
6133         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6134
6135         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6136         let channel_reserve = chan_stat.channel_reserve_msat;
6137         let feerate = get_feerate!(nodes[0], chan.2);
6138         let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6139
6140         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6141         let amt_1 = 20000;
6142         let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors) - amt_1;
6143         let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
6144         let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
6145
6146         // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6147         nodes[0].node.send_payment(&route_1, payment_hash_1, &Some(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
6148         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6149         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6150         let payment_id_2 = PaymentId(nodes[0].keys_manager.get_secure_random_bytes());
6151         nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2), payment_id_2).unwrap();
6152         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6153         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6154
6155         // Flush the pending fee update.
6156         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6157         let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6158         check_added_monitors!(nodes[1], 1);
6159         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6160         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6161         check_added_monitors!(nodes[0], 2);
6162
6163         // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6164         // but now that the fee has been raised the second payment will now fail, causing us
6165         // to surface its failure to the user. The first payment should succeed.
6166         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6167         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6168         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);
6169         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 {}",
6170                 hex::encode(payment_hash_2.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6171         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6172
6173         // Check that the second payment failed to be sent out.
6174         let events = nodes[0].node.get_and_clear_pending_events();
6175         assert_eq!(events.len(), 1);
6176         match &events[0] {
6177                 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, ref network_update, ref all_paths_failed, ref short_channel_id, .. } => {
6178                         assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
6179                         assert_eq!(payment_hash_2.clone(), *payment_hash);
6180                         assert_eq!(*payment_failed_permanently, false);
6181                         assert_eq!(*all_paths_failed, true);
6182                         assert_eq!(*network_update, None);
6183                         assert_eq!(*short_channel_id, Some(route_2.paths[0][0].short_channel_id));
6184                 },
6185                 _ => panic!("Unexpected event"),
6186         }
6187
6188         // Complete the first payment and the RAA from the fee update.
6189         let (payment_event, send_raa_event) = {
6190                 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6191                 assert_eq!(msgs.len(), 2);
6192                 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6193         };
6194         let raa = match send_raa_event {
6195                 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6196                 _ => panic!("Unexpected event"),
6197         };
6198         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6199         check_added_monitors!(nodes[1], 1);
6200         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6201         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6202         let events = nodes[1].node.get_and_clear_pending_events();
6203         assert_eq!(events.len(), 1);
6204         match events[0] {
6205                 Event::PendingHTLCsForwardable { .. } => {},
6206                 _ => panic!("Unexpected event"),
6207         }
6208         nodes[1].node.process_pending_htlc_forwards();
6209         let events = nodes[1].node.get_and_clear_pending_events();
6210         assert_eq!(events.len(), 1);
6211         match events[0] {
6212                 Event::PaymentReceived { .. } => {},
6213                 _ => panic!("Unexpected event"),
6214         }
6215         nodes[1].node.claim_funds(payment_preimage_1);
6216         check_added_monitors!(nodes[1], 1);
6217         expect_payment_claimed!(nodes[1], payment_hash_1, amt_1);
6218
6219         let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6220         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6221         commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6222         expect_payment_sent!(nodes[0], payment_preimage_1);
6223 }
6224
6225 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6226 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6227 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6228 // once it's freed.
6229 #[test]
6230 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6231         let chanmon_cfgs = create_chanmon_cfgs(3);
6232         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6233         // When this test was written, the default base fee floated based on the HTLC count.
6234         // It is now fixed, so we simply set the fee to the expected value here.
6235         let mut config = test_default_channel_config();
6236         config.channel_config.forwarding_fee_base_msat = 196;
6237         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
6238         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6239         let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6240         let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6241
6242         // First nodes[1] generates an update_fee, setting the channel's
6243         // pending_update_fee.
6244         {
6245                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
6246                 *feerate_lock += 20;
6247         }
6248         nodes[1].node.timer_tick_occurred();
6249         check_added_monitors!(nodes[1], 1);
6250
6251         let events = nodes[1].node.get_and_clear_pending_msg_events();
6252         assert_eq!(events.len(), 1);
6253         let (update_msg, commitment_signed) = match events[0] {
6254                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6255                         (update_fee.as_ref(), commitment_signed)
6256                 },
6257                 _ => panic!("Unexpected event"),
6258         };
6259
6260         nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6261
6262         let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
6263         let channel_reserve = chan_stat.channel_reserve_msat;
6264         let feerate = get_feerate!(nodes[0], chan_0_1.2);
6265         let opt_anchors = get_opt_anchors!(nodes[0], chan_0_1.2);
6266
6267         // Send a payment which passes reserve checks but gets stuck in the holding cell.
6268         let feemsat = 239;
6269         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
6270         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors) - total_routing_fee_msat;
6271         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
6272         let payment_event = {
6273                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6274                 check_added_monitors!(nodes[0], 1);
6275
6276                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6277                 assert_eq!(events.len(), 1);
6278
6279                 SendEvent::from_event(events.remove(0))
6280         };
6281         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6282         check_added_monitors!(nodes[1], 0);
6283         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6284         expect_pending_htlcs_forwardable!(nodes[1]);
6285
6286         chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
6287         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6288
6289         // Flush the pending fee update.
6290         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6291         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6292         check_added_monitors!(nodes[2], 1);
6293         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6294         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6295         check_added_monitors!(nodes[1], 2);
6296
6297         // A final RAA message is generated to finalize the fee update.
6298         let events = nodes[1].node.get_and_clear_pending_msg_events();
6299         assert_eq!(events.len(), 1);
6300
6301         let raa_msg = match &events[0] {
6302                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6303                         msg.clone()
6304                 },
6305                 _ => panic!("Unexpected event"),
6306         };
6307
6308         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6309         check_added_monitors!(nodes[2], 1);
6310         assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6311
6312         // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6313         let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6314         assert_eq!(process_htlc_forwards_event.len(), 2);
6315         match &process_htlc_forwards_event[0] {
6316                 &Event::PendingHTLCsForwardable { .. } => {},
6317                 _ => panic!("Unexpected event"),
6318         }
6319
6320         // In response, we call ChannelManager's process_pending_htlc_forwards
6321         nodes[1].node.process_pending_htlc_forwards();
6322         check_added_monitors!(nodes[1], 1);
6323
6324         // This causes the HTLC to be failed backwards.
6325         let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6326         assert_eq!(fail_event.len(), 1);
6327         let (fail_msg, commitment_signed) = match &fail_event[0] {
6328                 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6329                         assert_eq!(updates.update_add_htlcs.len(), 0);
6330                         assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6331                         assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6332                         assert_eq!(updates.update_fail_htlcs.len(), 1);
6333                         (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6334                 },
6335                 _ => panic!("Unexpected event"),
6336         };
6337
6338         // Pass the failure messages back to nodes[0].
6339         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6340         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6341
6342         // Complete the HTLC failure+removal process.
6343         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6344         check_added_monitors!(nodes[0], 1);
6345         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6346         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6347         check_added_monitors!(nodes[1], 2);
6348         let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6349         assert_eq!(final_raa_event.len(), 1);
6350         let raa = match &final_raa_event[0] {
6351                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6352                 _ => panic!("Unexpected event"),
6353         };
6354         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6355         expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6356         check_added_monitors!(nodes[0], 1);
6357 }
6358
6359 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6360 // 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.
6361 //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.
6362
6363 #[test]
6364 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6365         //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6366         let chanmon_cfgs = create_chanmon_cfgs(2);
6367         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6368         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6369         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6370         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6371
6372         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6373         route.paths[0][0].fee_msat = 100;
6374
6375         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 },
6376                 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6377         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6378         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6379 }
6380
6381 #[test]
6382 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6383         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6384         let chanmon_cfgs = create_chanmon_cfgs(2);
6385         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6386         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6387         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6388         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6389
6390         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6391         route.paths[0][0].fee_msat = 0;
6392         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 },
6393                 assert_eq!(err, "Cannot send 0-msat HTLC"));
6394
6395         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6396         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6397 }
6398
6399 #[test]
6400 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6401         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6402         let chanmon_cfgs = create_chanmon_cfgs(2);
6403         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6404         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6405         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6406         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6407
6408         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6409         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6410         check_added_monitors!(nodes[0], 1);
6411         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6412         updates.update_add_htlcs[0].amount_msat = 0;
6413
6414         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6415         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6416         check_closed_broadcast!(nodes[1], true).unwrap();
6417         check_added_monitors!(nodes[1], 1);
6418         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
6419 }
6420
6421 #[test]
6422 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6423         //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6424         //It is enforced when constructing a route.
6425         let chanmon_cfgs = create_chanmon_cfgs(2);
6426         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6427         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6428         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6429         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6430
6431         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
6432                 .with_features(channelmanager::provided_invoice_features());
6433         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000, 0);
6434         route.paths[0].last_mut().unwrap().cltv_expiry_delta = 500000001;
6435         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)), true, APIError::RouteError { ref err },
6436                 assert_eq!(err, &"Channel CLTV overflowed?"));
6437 }
6438
6439 #[test]
6440 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6441         //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.
6442         //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6443         //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6444         let chanmon_cfgs = create_chanmon_cfgs(2);
6445         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6446         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6447         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6448         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6449         let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6450
6451         for i in 0..max_accepted_htlcs {
6452                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6453                 let payment_event = {
6454                         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6455                         check_added_monitors!(nodes[0], 1);
6456
6457                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6458                         assert_eq!(events.len(), 1);
6459                         if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6460                                 assert_eq!(htlcs[0].htlc_id, i);
6461                         } else {
6462                                 assert!(false);
6463                         }
6464                         SendEvent::from_event(events.remove(0))
6465                 };
6466                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6467                 check_added_monitors!(nodes[1], 0);
6468                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6469
6470                 expect_pending_htlcs_forwardable!(nodes[1]);
6471                 expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6472         }
6473         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6474         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 },
6475                 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6476
6477         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6478         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6479 }
6480
6481 #[test]
6482 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6483         //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.
6484         let chanmon_cfgs = create_chanmon_cfgs(2);
6485         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6486         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6487         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6488         let channel_value = 100000;
6489         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6490         let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6491
6492         send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6493
6494         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6495         // Manually create a route over our max in flight (which our router normally automatically
6496         // limits us to.
6497         route.paths[0][0].fee_msat =  max_in_flight + 1;
6498         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 },
6499                 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)));
6500
6501         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6502         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);
6503
6504         send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6505 }
6506
6507 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6508 #[test]
6509 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6510         //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6511         let chanmon_cfgs = create_chanmon_cfgs(2);
6512         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6513         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6514         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6515         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6516         let htlc_minimum_msat: u64;
6517         {
6518                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6519                 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6520                 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6521         }
6522
6523         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6524         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6525         check_added_monitors!(nodes[0], 1);
6526         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6527         updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6528         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6529         assert!(nodes[1].node.list_channels().is_empty());
6530         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6531         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()));
6532         check_added_monitors!(nodes[1], 1);
6533         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6534 }
6535
6536 #[test]
6537 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6538         //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
6539         let chanmon_cfgs = create_chanmon_cfgs(2);
6540         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6541         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6542         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6543         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6544
6545         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6546         let channel_reserve = chan_stat.channel_reserve_msat;
6547         let feerate = get_feerate!(nodes[0], chan.2);
6548         let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6549         // The 2* and +1 are for the fee spike reserve.
6550         let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6551
6552         let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6553         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6554         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6555         check_added_monitors!(nodes[0], 1);
6556         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6557
6558         // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6559         // at this time channel-initiatee receivers are not required to enforce that senders
6560         // respect the fee_spike_reserve.
6561         updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6562         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6563
6564         assert!(nodes[1].node.list_channels().is_empty());
6565         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6566         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6567         check_added_monitors!(nodes[1], 1);
6568         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6569 }
6570
6571 #[test]
6572 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6573         //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6574         //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6575         let chanmon_cfgs = create_chanmon_cfgs(2);
6576         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6577         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6578         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6579         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6580
6581         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3999999);
6582         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6583         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6584         let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6585         let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &Some(our_payment_secret), cur_height, &None).unwrap();
6586         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6587
6588         let mut msg = msgs::UpdateAddHTLC {
6589                 channel_id: chan.2,
6590                 htlc_id: 0,
6591                 amount_msat: 1000,
6592                 payment_hash: our_payment_hash,
6593                 cltv_expiry: htlc_cltv,
6594                 onion_routing_packet: onion_packet.clone(),
6595         };
6596
6597         for i in 0..super::channel::OUR_MAX_HTLCS {
6598                 msg.htlc_id = i as u64;
6599                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6600         }
6601         msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6602         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6603
6604         assert!(nodes[1].node.list_channels().is_empty());
6605         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6606         assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6607         check_added_monitors!(nodes[1], 1);
6608         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6609 }
6610
6611 #[test]
6612 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6613         //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6614         let chanmon_cfgs = create_chanmon_cfgs(2);
6615         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6616         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6617         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6618         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6619
6620         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6621         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6622         check_added_monitors!(nodes[0], 1);
6623         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6624         updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6625         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6626
6627         assert!(nodes[1].node.list_channels().is_empty());
6628         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6629         assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6630         check_added_monitors!(nodes[1], 1);
6631         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6632 }
6633
6634 #[test]
6635 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6636         //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6637         let chanmon_cfgs = create_chanmon_cfgs(2);
6638         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6639         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6640         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6641
6642         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6643         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6644         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6645         check_added_monitors!(nodes[0], 1);
6646         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6647         updates.update_add_htlcs[0].cltv_expiry = 500000000;
6648         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6649
6650         assert!(nodes[1].node.list_channels().is_empty());
6651         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6652         assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6653         check_added_monitors!(nodes[1], 1);
6654         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6655 }
6656
6657 #[test]
6658 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6659         //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6660         // We test this by first testing that that repeated HTLCs pass commitment signature checks
6661         // after disconnect and that non-sequential htlc_ids result in a channel failure.
6662         let chanmon_cfgs = create_chanmon_cfgs(2);
6663         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6664         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6665         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6666
6667         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6668         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6669         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6670         check_added_monitors!(nodes[0], 1);
6671         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6672         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6673
6674         //Disconnect and Reconnect
6675         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6676         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6677         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
6678         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6679         assert_eq!(reestablish_1.len(), 1);
6680         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
6681         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6682         assert_eq!(reestablish_2.len(), 1);
6683         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6684         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6685         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6686         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6687
6688         //Resend HTLC
6689         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6690         assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6691         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6692         check_added_monitors!(nodes[1], 1);
6693         let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6694
6695         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6696
6697         assert!(nodes[1].node.list_channels().is_empty());
6698         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6699         assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6700         check_added_monitors!(nodes[1], 1);
6701         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6702 }
6703
6704 #[test]
6705 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6706         //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.
6707
6708         let chanmon_cfgs = create_chanmon_cfgs(2);
6709         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6710         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6711         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6712         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6713         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6714         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6715
6716         check_added_monitors!(nodes[0], 1);
6717         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6718         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6719
6720         let update_msg = msgs::UpdateFulfillHTLC{
6721                 channel_id: chan.2,
6722                 htlc_id: 0,
6723                 payment_preimage: our_payment_preimage,
6724         };
6725
6726         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6727
6728         assert!(nodes[0].node.list_channels().is_empty());
6729         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6730         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()));
6731         check_added_monitors!(nodes[0], 1);
6732         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6733 }
6734
6735 #[test]
6736 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6737         //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.
6738
6739         let chanmon_cfgs = create_chanmon_cfgs(2);
6740         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6741         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6742         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6743         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6744
6745         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6746         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6747         check_added_monitors!(nodes[0], 1);
6748         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6749         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6750
6751         let update_msg = msgs::UpdateFailHTLC{
6752                 channel_id: chan.2,
6753                 htlc_id: 0,
6754                 reason: msgs::OnionErrorPacket { data: Vec::new()},
6755         };
6756
6757         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6758
6759         assert!(nodes[0].node.list_channels().is_empty());
6760         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6761         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()));
6762         check_added_monitors!(nodes[0], 1);
6763         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6764 }
6765
6766 #[test]
6767 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6768         //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.
6769
6770         let chanmon_cfgs = create_chanmon_cfgs(2);
6771         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6772         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6773         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6774         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6775
6776         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6777         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6778         check_added_monitors!(nodes[0], 1);
6779         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6780         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6781         let update_msg = msgs::UpdateFailMalformedHTLC{
6782                 channel_id: chan.2,
6783                 htlc_id: 0,
6784                 sha256_of_onion: [1; 32],
6785                 failure_code: 0x8000,
6786         };
6787
6788         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6789
6790         assert!(nodes[0].node.list_channels().is_empty());
6791         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6792         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()));
6793         check_added_monitors!(nodes[0], 1);
6794         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6795 }
6796
6797 #[test]
6798 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6799         //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6800
6801         let chanmon_cfgs = create_chanmon_cfgs(2);
6802         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6803         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6804         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6805         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6806
6807         let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6808
6809         nodes[1].node.claim_funds(our_payment_preimage);
6810         check_added_monitors!(nodes[1], 1);
6811         expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6812
6813         let events = nodes[1].node.get_and_clear_pending_msg_events();
6814         assert_eq!(events.len(), 1);
6815         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6816                 match events[0] {
6817                         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, .. } } => {
6818                                 assert!(update_add_htlcs.is_empty());
6819                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6820                                 assert!(update_fail_htlcs.is_empty());
6821                                 assert!(update_fail_malformed_htlcs.is_empty());
6822                                 assert!(update_fee.is_none());
6823                                 update_fulfill_htlcs[0].clone()
6824                         },
6825                         _ => panic!("Unexpected event"),
6826                 }
6827         };
6828
6829         update_fulfill_msg.htlc_id = 1;
6830
6831         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6832
6833         assert!(nodes[0].node.list_channels().is_empty());
6834         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6835         assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6836         check_added_monitors!(nodes[0], 1);
6837         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6838 }
6839
6840 #[test]
6841 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6842         //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.
6843
6844         let chanmon_cfgs = create_chanmon_cfgs(2);
6845         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6846         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6847         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6848         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6849
6850         let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6851
6852         nodes[1].node.claim_funds(our_payment_preimage);
6853         check_added_monitors!(nodes[1], 1);
6854         expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6855
6856         let events = nodes[1].node.get_and_clear_pending_msg_events();
6857         assert_eq!(events.len(), 1);
6858         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6859                 match events[0] {
6860                         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, .. } } => {
6861                                 assert!(update_add_htlcs.is_empty());
6862                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6863                                 assert!(update_fail_htlcs.is_empty());
6864                                 assert!(update_fail_malformed_htlcs.is_empty());
6865                                 assert!(update_fee.is_none());
6866                                 update_fulfill_htlcs[0].clone()
6867                         },
6868                         _ => panic!("Unexpected event"),
6869                 }
6870         };
6871
6872         update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6873
6874         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6875
6876         assert!(nodes[0].node.list_channels().is_empty());
6877         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6878         assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6879         check_added_monitors!(nodes[0], 1);
6880         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6881 }
6882
6883 #[test]
6884 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6885         //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.
6886
6887         let chanmon_cfgs = create_chanmon_cfgs(2);
6888         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6889         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6890         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6891         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6892
6893         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6894         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6895         check_added_monitors!(nodes[0], 1);
6896
6897         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6898         updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6899
6900         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6901         check_added_monitors!(nodes[1], 0);
6902         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6903
6904         let events = nodes[1].node.get_and_clear_pending_msg_events();
6905
6906         let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6907                 match events[0] {
6908                         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, .. } } => {
6909                                 assert!(update_add_htlcs.is_empty());
6910                                 assert!(update_fulfill_htlcs.is_empty());
6911                                 assert!(update_fail_htlcs.is_empty());
6912                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6913                                 assert!(update_fee.is_none());
6914                                 update_fail_malformed_htlcs[0].clone()
6915                         },
6916                         _ => panic!("Unexpected event"),
6917                 }
6918         };
6919         update_msg.failure_code &= !0x8000;
6920         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6921
6922         assert!(nodes[0].node.list_channels().is_empty());
6923         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6924         assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6925         check_added_monitors!(nodes[0], 1);
6926         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6927 }
6928
6929 #[test]
6930 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6931         //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6932         //    * 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.
6933
6934         let chanmon_cfgs = create_chanmon_cfgs(3);
6935         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6936         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6937         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6938         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6939         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6940
6941         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
6942
6943         //First hop
6944         let mut payment_event = {
6945                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6946                 check_added_monitors!(nodes[0], 1);
6947                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6948                 assert_eq!(events.len(), 1);
6949                 SendEvent::from_event(events.remove(0))
6950         };
6951         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6952         check_added_monitors!(nodes[1], 0);
6953         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6954         expect_pending_htlcs_forwardable!(nodes[1]);
6955         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6956         assert_eq!(events_2.len(), 1);
6957         check_added_monitors!(nodes[1], 1);
6958         payment_event = SendEvent::from_event(events_2.remove(0));
6959         assert_eq!(payment_event.msgs.len(), 1);
6960
6961         //Second Hop
6962         payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6963         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6964         check_added_monitors!(nodes[2], 0);
6965         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6966
6967         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6968         assert_eq!(events_3.len(), 1);
6969         let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6970                 match events_3[0] {
6971                         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 } } => {
6972                                 assert!(update_add_htlcs.is_empty());
6973                                 assert!(update_fulfill_htlcs.is_empty());
6974                                 assert!(update_fail_htlcs.is_empty());
6975                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6976                                 assert!(update_fee.is_none());
6977                                 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6978                         },
6979                         _ => panic!("Unexpected event"),
6980                 }
6981         };
6982
6983         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6984
6985         check_added_monitors!(nodes[1], 0);
6986         commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6987         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 }]);
6988         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6989         assert_eq!(events_4.len(), 1);
6990
6991         //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6992         match events_4[0] {
6993                 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, .. } } => {
6994                         assert!(update_add_htlcs.is_empty());
6995                         assert!(update_fulfill_htlcs.is_empty());
6996                         assert_eq!(update_fail_htlcs.len(), 1);
6997                         assert!(update_fail_malformed_htlcs.is_empty());
6998                         assert!(update_fee.is_none());
6999                 },
7000                 _ => panic!("Unexpected event"),
7001         };
7002
7003         check_added_monitors!(nodes[1], 1);
7004 }
7005
7006 #[test]
7007 fn test_channel_failed_after_message_with_badonion_node_perm_bits_set() {
7008         let chanmon_cfgs = create_chanmon_cfgs(3);
7009         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7010         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7011         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7012         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7013         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7014
7015         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100_000);
7016
7017         // First hop
7018         let mut payment_event = {
7019                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
7020                 check_added_monitors!(nodes[0], 1);
7021                 SendEvent::from_node(&nodes[0])
7022         };
7023
7024         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7025         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7026         expect_pending_htlcs_forwardable!(nodes[1]);
7027         check_added_monitors!(nodes[1], 1);
7028         payment_event = SendEvent::from_node(&nodes[1]);
7029         assert_eq!(payment_event.msgs.len(), 1);
7030
7031         // Second Hop
7032         payment_event.msgs[0].onion_routing_packet.version = 1; // Trigger an invalid_onion_version error
7033         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
7034         check_added_monitors!(nodes[2], 0);
7035         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
7036
7037         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
7038         assert_eq!(events_3.len(), 1);
7039         match events_3[0] {
7040                 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
7041                         let mut update_msg = updates.update_fail_malformed_htlcs[0].clone();
7042                         // Set the NODE bit (BADONION and PERM already set in invalid_onion_version error)
7043                         update_msg.failure_code |= 0x2000;
7044
7045                         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg);
7046                         commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true);
7047                 },
7048                 _ => panic!("Unexpected event"),
7049         }
7050
7051         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
7052                 vec![HTLCDestination::NextHopChannel {
7053                         node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
7054         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
7055         assert_eq!(events_4.len(), 1);
7056         check_added_monitors!(nodes[1], 1);
7057
7058         match events_4[0] {
7059                 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
7060                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
7061                         commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
7062                 },
7063                 _ => panic!("Unexpected event"),
7064         }
7065
7066         let events_5 = nodes[0].node.get_and_clear_pending_events();
7067         assert_eq!(events_5.len(), 1);
7068
7069         // Expect a PaymentPathFailed event with a ChannelFailure network update for the channel between
7070         // the node originating the error to its next hop.
7071         match events_5[0] {
7072                 Event::PaymentPathFailed { network_update:
7073                         Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent }), error_code, ..
7074                 } => {
7075                         assert_eq!(short_channel_id, chan_2.0.contents.short_channel_id);
7076                         assert!(is_permanent);
7077                         assert_eq!(error_code, Some(0x8000|0x4000|0x2000|4));
7078                 },
7079                 _ => panic!("Unexpected event"),
7080         }
7081
7082         // TODO: Test actual removal of channel from NetworkGraph when it's implemented.
7083 }
7084
7085 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
7086         // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
7087         // 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
7088         // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
7089
7090         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7091         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7092         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7093         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7094         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7095         let chan =create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7096
7097         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7098
7099         // We route 2 dust-HTLCs between A and B
7100         let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7101         let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7102         route_payment(&nodes[0], &[&nodes[1]], 1000000);
7103
7104         // Cache one local commitment tx as previous
7105         let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7106
7107         // Fail one HTLC to prune it in the will-be-latest-local commitment tx
7108         nodes[1].node.fail_htlc_backwards(&payment_hash_2);
7109         check_added_monitors!(nodes[1], 0);
7110         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
7111         check_added_monitors!(nodes[1], 1);
7112
7113         let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7114         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
7115         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
7116         check_added_monitors!(nodes[0], 1);
7117
7118         // Cache one local commitment tx as lastest
7119         let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7120
7121         let events = nodes[0].node.get_and_clear_pending_msg_events();
7122         match events[0] {
7123                 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
7124                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7125                 },
7126                 _ => panic!("Unexpected event"),
7127         }
7128         match events[1] {
7129                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
7130                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7131                 },
7132                 _ => panic!("Unexpected event"),
7133         }
7134
7135         assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
7136         // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7137         if announce_latest {
7138                 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
7139         } else {
7140                 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
7141         }
7142
7143         check_closed_broadcast!(nodes[0], true);
7144         check_added_monitors!(nodes[0], 1);
7145         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7146
7147         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7148         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7149         let events = nodes[0].node.get_and_clear_pending_events();
7150         // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
7151         assert_eq!(events.len(), 2);
7152         let mut first_failed = false;
7153         for event in events {
7154                 match event {
7155                         Event::PaymentPathFailed { payment_hash, .. } => {
7156                                 if payment_hash == payment_hash_1 {
7157                                         assert!(!first_failed);
7158                                         first_failed = true;
7159                                 } else {
7160                                         assert_eq!(payment_hash, payment_hash_2);
7161                                 }
7162                         }
7163                         _ => panic!("Unexpected event"),
7164                 }
7165         }
7166 }
7167
7168 #[test]
7169 fn test_failure_delay_dust_htlc_local_commitment() {
7170         do_test_failure_delay_dust_htlc_local_commitment(true);
7171         do_test_failure_delay_dust_htlc_local_commitment(false);
7172 }
7173
7174 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7175         // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7176         // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7177         // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7178         // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7179         // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7180         // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7181
7182         let chanmon_cfgs = create_chanmon_cfgs(3);
7183         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7184         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7185         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7186         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7187
7188         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7189
7190         let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7191         let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7192
7193         let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7194         let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7195
7196         // We revoked bs_commitment_tx
7197         if revoked {
7198                 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7199                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
7200         }
7201
7202         let mut timeout_tx = Vec::new();
7203         if local {
7204                 // We fail dust-HTLC 1 by broadcast of local commitment tx
7205                 mine_transaction(&nodes[0], &as_commitment_tx[0]);
7206                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7207                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7208                 expect_payment_failed!(nodes[0], dust_hash, false);
7209
7210                 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
7211                 check_closed_broadcast!(nodes[0], true);
7212                 check_added_monitors!(nodes[0], 1);
7213                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7214                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
7215                 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7216                 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7217                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7218                 mine_transaction(&nodes[0], &timeout_tx[0]);
7219                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7220                 expect_payment_failed!(nodes[0], non_dust_hash, false);
7221         } else {
7222                 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7223                 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
7224                 check_closed_broadcast!(nodes[0], true);
7225                 check_added_monitors!(nodes[0], 1);
7226                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7227                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7228
7229                 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7230                 timeout_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().drain(..)
7231                         .filter(|tx| tx.input[0].previous_output.txid == bs_commitment_tx[0].txid()).collect();
7232                 check_spends!(timeout_tx[0], bs_commitment_tx[0]);
7233                 // For both a revoked or non-revoked commitment transaction, after ANTI_REORG_DELAY the
7234                 // dust HTLC should have been failed.
7235                 expect_payment_failed!(nodes[0], dust_hash, false);
7236
7237                 if !revoked {
7238                         assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7239                 } else {
7240                         assert_eq!(timeout_tx[0].lock_time.0, 0);
7241                 }
7242                 // We fail non-dust-HTLC 2 by broadcast of local timeout/revocation-claim tx
7243                 mine_transaction(&nodes[0], &timeout_tx[0]);
7244                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7245                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7246                 expect_payment_failed!(nodes[0], non_dust_hash, false);
7247         }
7248 }
7249
7250 #[test]
7251 fn test_sweep_outbound_htlc_failure_update() {
7252         do_test_sweep_outbound_htlc_failure_update(false, true);
7253         do_test_sweep_outbound_htlc_failure_update(false, false);
7254         do_test_sweep_outbound_htlc_failure_update(true, false);
7255 }
7256
7257 #[test]
7258 fn test_user_configurable_csv_delay() {
7259         // We test our channel constructors yield errors when we pass them absurd csv delay
7260
7261         let mut low_our_to_self_config = UserConfig::default();
7262         low_our_to_self_config.channel_handshake_config.our_to_self_delay = 6;
7263         let mut high_their_to_self_config = UserConfig::default();
7264         high_their_to_self_config.channel_handshake_limits.their_to_self_delay = 100;
7265         let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7266         let chanmon_cfgs = create_chanmon_cfgs(2);
7267         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7268         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7269         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7270
7271         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7272         if let Err(error) = Channel::new_outbound(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7273                 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &channelmanager::provided_init_features(), 1000000, 1000000, 0,
7274                 &low_our_to_self_config, 0, 42)
7275         {
7276                 match error {
7277                         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())); },
7278                         _ => panic!("Unexpected event"),
7279                 }
7280         } else { assert!(false) }
7281
7282         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7283         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7284         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7285         open_channel.to_self_delay = 200;
7286         if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7287                 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &channelmanager::provided_init_features(), &open_channel, 0,
7288                 &low_our_to_self_config, 0, &nodes[0].logger, 42)
7289         {
7290                 match error {
7291                         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()));  },
7292                         _ => panic!("Unexpected event"),
7293                 }
7294         } else { assert!(false); }
7295
7296         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7297         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7298         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()));
7299         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7300         accept_channel.to_self_delay = 200;
7301         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_channel);
7302         let reason_msg;
7303         if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7304                 match action {
7305                         &ErrorAction::SendErrorMessage { ref msg } => {
7306                                 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()));
7307                                 reason_msg = msg.data.clone();
7308                         },
7309                         _ => { panic!(); }
7310                 }
7311         } else { panic!(); }
7312         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg });
7313
7314         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7315         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7316         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7317         open_channel.to_self_delay = 200;
7318         if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7319                 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &channelmanager::provided_init_features(), &open_channel, 0,
7320                 &high_their_to_self_config, 0, &nodes[0].logger, 42)
7321         {
7322                 match error {
7323                         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())); },
7324                         _ => panic!("Unexpected event"),
7325                 }
7326         } else { assert!(false); }
7327 }
7328
7329 fn do_test_data_loss_protect(reconnect_panicing: bool) {
7330         // When we get a data_loss_protect proving we're behind, we immediately panic as the
7331         // chain::Watch API requirements have been violated (e.g. the user restored from a backup). The
7332         // panic message informs the user they should force-close without broadcasting, which is tested
7333         // if `reconnect_panicing` is not set.
7334         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7335         // We broadcast during Drop because chanmon is out of sync with chanmgr, which would cause a panic
7336         // during signing due to revoked tx
7337         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7338         let persister;
7339         let new_chain_monitor;
7340         let nodes_0_deserialized;
7341         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7342         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7343         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7344
7345         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7346
7347         // Cache node A state before any channel update
7348         let previous_node_state = nodes[0].node.encode();
7349         let previous_chain_monitor_state = get_monitor!(nodes[0], chan.2).encode();
7350
7351         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7352         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7353
7354         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7355         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7356
7357         reload_node!(nodes[0], previous_node_state, &[&previous_chain_monitor_state], persister, new_chain_monitor, nodes_0_deserialized);
7358
7359         if reconnect_panicing {
7360                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
7361                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
7362
7363                 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7364
7365                 // Check we close channel detecting A is fallen-behind
7366                 // Check that we sent the warning message when we detected that A has fallen behind,
7367                 // and give the possibility for A to recover from the warning.
7368                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7369                 let warn_msg = "Peer attempted to reestablish channel with a very old local commitment transaction".to_owned();
7370                 assert!(check_warn_msg!(nodes[1], nodes[0].node.get_our_node_id(), chan.2).contains(&warn_msg));
7371
7372                 {
7373                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7374                         // The node B should not broadcast the transaction to force close the channel!
7375                         assert!(node_txn.is_empty());
7376                 }
7377
7378                 let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7379                 // Check A panics upon seeing proof it has fallen behind.
7380                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7381                 return; // By this point we should have panic'ed!
7382         }
7383
7384         nodes[0].node.force_close_without_broadcasting_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
7385         check_added_monitors!(nodes[0], 1);
7386         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
7387         {
7388                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7389                 assert_eq!(node_txn.len(), 0);
7390         }
7391
7392         for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7393                 if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7394                 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7395                         match action {
7396                                 &ErrorAction::SendErrorMessage { ref msg } => {
7397                                         assert_eq!(msg.data, "Channel force-closed");
7398                                 },
7399                                 _ => panic!("Unexpected event!"),
7400                         }
7401                 } else {
7402                         panic!("Unexpected event {:?}", msg)
7403                 }
7404         }
7405
7406         // after the warning message sent by B, we should not able to
7407         // use the channel, or reconnect with success to the channel.
7408         assert!(nodes[0].node.list_usable_channels().is_empty());
7409         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
7410         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
7411         let retry_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7412
7413         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &retry_reestablish[0]);
7414         let mut err_msgs_0 = Vec::with_capacity(1);
7415         for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7416                 if let MessageSendEvent::HandleError { ref action, .. } = msg {
7417                         match action {
7418                                 &ErrorAction::SendErrorMessage { ref msg } => {
7419                                         assert_eq!(msg.data, "Failed to find corresponding channel");
7420                                         err_msgs_0.push(msg.clone());
7421                                 },
7422                                 _ => panic!("Unexpected event!"),
7423                         }
7424                 } else {
7425                         panic!("Unexpected event!");
7426                 }
7427         }
7428         assert_eq!(err_msgs_0.len(), 1);
7429         nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), &err_msgs_0[0]);
7430         assert!(nodes[1].node.list_usable_channels().is_empty());
7431         check_added_monitors!(nodes[1], 1);
7432         check_closed_event!(nodes[1], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "Failed to find corresponding channel".to_owned() });
7433         check_closed_broadcast!(nodes[1], false);
7434 }
7435
7436 #[test]
7437 #[should_panic]
7438 fn test_data_loss_protect_showing_stale_state_panics() {
7439         do_test_data_loss_protect(true);
7440 }
7441
7442 #[test]
7443 fn test_force_close_without_broadcast() {
7444         do_test_data_loss_protect(false);
7445 }
7446
7447 #[test]
7448 fn test_check_htlc_underpaying() {
7449         // Send payment through A -> B but A is maliciously
7450         // sending a probe payment (i.e less than expected value0
7451         // to B, B should refuse payment.
7452
7453         let chanmon_cfgs = create_chanmon_cfgs(2);
7454         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7455         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7456         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7457
7458         // Create some initial channels
7459         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7460
7461         let scorer = test_utils::TestScorer::with_penalty(0);
7462         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7463         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id()).with_features(channelmanager::provided_invoice_features());
7464         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();
7465         let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7466         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200).unwrap();
7467         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
7468         check_added_monitors!(nodes[0], 1);
7469
7470         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7471         assert_eq!(events.len(), 1);
7472         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7473         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7474         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7475
7476         // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7477         // and then will wait a second random delay before failing the HTLC back:
7478         expect_pending_htlcs_forwardable!(nodes[1]);
7479         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
7480
7481         // Node 3 is expecting payment of 100_000 but received 10_000,
7482         // it should fail htlc like we didn't know the preimage.
7483         nodes[1].node.process_pending_htlc_forwards();
7484
7485         let events = nodes[1].node.get_and_clear_pending_msg_events();
7486         assert_eq!(events.len(), 1);
7487         let (update_fail_htlc, commitment_signed) = match events[0] {
7488                 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 } } => {
7489                         assert!(update_add_htlcs.is_empty());
7490                         assert!(update_fulfill_htlcs.is_empty());
7491                         assert_eq!(update_fail_htlcs.len(), 1);
7492                         assert!(update_fail_malformed_htlcs.is_empty());
7493                         assert!(update_fee.is_none());
7494                         (update_fail_htlcs[0].clone(), commitment_signed)
7495                 },
7496                 _ => panic!("Unexpected event"),
7497         };
7498         check_added_monitors!(nodes[1], 1);
7499
7500         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7501         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7502
7503         // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7504         let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7505         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(CHAN_CONFIRM_DEPTH));
7506         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7507 }
7508
7509 #[test]
7510 fn test_announce_disable_channels() {
7511         // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7512         // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7513
7514         let chanmon_cfgs = create_chanmon_cfgs(2);
7515         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7516         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7517         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7518
7519         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7520         create_announced_chan_between_nodes(&nodes, 1, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7521         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7522
7523         // Disconnect peers
7524         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7525         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7526
7527         nodes[0].node.timer_tick_occurred(); // Enabled -> DisabledStaged
7528         nodes[0].node.timer_tick_occurred(); // DisabledStaged -> Disabled
7529         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7530         assert_eq!(msg_events.len(), 3);
7531         let mut chans_disabled = HashMap::new();
7532         for e in msg_events {
7533                 match e {
7534                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7535                                 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7536                                 // Check that each channel gets updated exactly once
7537                                 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7538                                         panic!("Generated ChannelUpdate for wrong chan!");
7539                                 }
7540                         },
7541                         _ => panic!("Unexpected event"),
7542                 }
7543         }
7544         // Reconnect peers
7545         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
7546         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7547         assert_eq!(reestablish_1.len(), 3);
7548         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
7549         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7550         assert_eq!(reestablish_2.len(), 3);
7551
7552         // Reestablish chan_1
7553         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7554         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7555         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7556         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7557         // Reestablish chan_2
7558         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7559         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7560         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7561         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7562         // Reestablish chan_3
7563         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7564         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7565         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7566         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7567
7568         nodes[0].node.timer_tick_occurred();
7569         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7570         nodes[0].node.timer_tick_occurred();
7571         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7572         assert_eq!(msg_events.len(), 3);
7573         for e in msg_events {
7574                 match e {
7575                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7576                                 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7577                                 match chans_disabled.remove(&msg.contents.short_channel_id) {
7578                                         // Each update should have a higher timestamp than the previous one, replacing
7579                                         // the old one.
7580                                         Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7581                                         None => panic!("Generated ChannelUpdate for wrong chan!"),
7582                                 }
7583                         },
7584                         _ => panic!("Unexpected event"),
7585                 }
7586         }
7587         // Check that each channel gets updated exactly once
7588         assert!(chans_disabled.is_empty());
7589 }
7590
7591 #[test]
7592 fn test_bump_penalty_txn_on_revoked_commitment() {
7593         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7594         // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7595
7596         let chanmon_cfgs = create_chanmon_cfgs(2);
7597         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7598         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7599         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7600
7601         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7602
7603         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7604         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id())
7605                 .with_features(channelmanager::provided_invoice_features());
7606         let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000, 30);
7607         send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7608
7609         let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7610         // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7611         assert_eq!(revoked_txn[0].output.len(), 4);
7612         assert_eq!(revoked_txn[0].input.len(), 1);
7613         assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7614         let revoked_txid = revoked_txn[0].txid();
7615
7616         let mut penalty_sum = 0;
7617         for outp in revoked_txn[0].output.iter() {
7618                 if outp.script_pubkey.is_v0_p2wsh() {
7619                         penalty_sum += outp.value;
7620                 }
7621         }
7622
7623         // Connect blocks to change height_timer range to see if we use right soonest_timelock
7624         let header_114 = connect_blocks(&nodes[1], 14);
7625
7626         // Actually revoke tx by claiming a HTLC
7627         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7628         let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7629         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] });
7630         check_added_monitors!(nodes[1], 1);
7631
7632         // One or more justice tx should have been broadcast, check it
7633         let penalty_1;
7634         let feerate_1;
7635         {
7636                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7637                 assert_eq!(node_txn.len(), 2); // justice tx (broadcasted from ChannelMonitor) + local commitment tx
7638                 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7639                 assert_eq!(node_txn[0].output.len(), 1);
7640                 check_spends!(node_txn[0], revoked_txn[0]);
7641                 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7642                 feerate_1 = fee_1 * 1000 / node_txn[0].weight() as u64;
7643                 penalty_1 = node_txn[0].txid();
7644                 node_txn.clear();
7645         };
7646
7647         // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7648         connect_blocks(&nodes[1], 15);
7649         let mut penalty_2 = penalty_1;
7650         let mut feerate_2 = 0;
7651         {
7652                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7653                 assert_eq!(node_txn.len(), 1);
7654                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7655                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7656                         assert_eq!(node_txn[0].output.len(), 1);
7657                         check_spends!(node_txn[0], revoked_txn[0]);
7658                         penalty_2 = node_txn[0].txid();
7659                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7660                         assert_ne!(penalty_2, penalty_1);
7661                         let fee_2 = penalty_sum - node_txn[0].output[0].value;
7662                         feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7663                         // Verify 25% bump heuristic
7664                         assert!(feerate_2 * 100 >= feerate_1 * 125);
7665                         node_txn.clear();
7666                 }
7667         }
7668         assert_ne!(feerate_2, 0);
7669
7670         // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7671         connect_blocks(&nodes[1], 1);
7672         let penalty_3;
7673         let mut feerate_3 = 0;
7674         {
7675                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7676                 assert_eq!(node_txn.len(), 1);
7677                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7678                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7679                         assert_eq!(node_txn[0].output.len(), 1);
7680                         check_spends!(node_txn[0], revoked_txn[0]);
7681                         penalty_3 = node_txn[0].txid();
7682                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7683                         assert_ne!(penalty_3, penalty_2);
7684                         let fee_3 = penalty_sum - node_txn[0].output[0].value;
7685                         feerate_3 = fee_3 * 1000 / node_txn[0].weight() as u64;
7686                         // Verify 25% bump heuristic
7687                         assert!(feerate_3 * 100 >= feerate_2 * 125);
7688                         node_txn.clear();
7689                 }
7690         }
7691         assert_ne!(feerate_3, 0);
7692
7693         nodes[1].node.get_and_clear_pending_events();
7694         nodes[1].node.get_and_clear_pending_msg_events();
7695 }
7696
7697 #[test]
7698 fn test_bump_penalty_txn_on_revoked_htlcs() {
7699         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7700         // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7701
7702         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7703         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7704         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7705         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7706         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7707
7708         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7709         // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7710         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id()).with_features(channelmanager::provided_invoice_features());
7711         let scorer = test_utils::TestScorer::with_penalty(0);
7712         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7713         let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None,
7714                 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7715         let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7716         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id()).with_features(channelmanager::provided_invoice_features());
7717         let route = get_route(&nodes[1].node.get_our_node_id(), &payment_params, &nodes[1].network_graph.read_only(), None,
7718                 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7719         send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7720
7721         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7722         assert_eq!(revoked_local_txn[0].input.len(), 1);
7723         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7724
7725         // Revoke local commitment tx
7726         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7727
7728         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7729         // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7730         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] });
7731         check_closed_broadcast!(nodes[1], true);
7732         check_added_monitors!(nodes[1], 1);
7733         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7734         connect_blocks(&nodes[1], 49); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7735
7736         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
7737         assert_eq!(revoked_htlc_txn.len(), 3);
7738         check_spends!(revoked_htlc_txn[1], chan.3);
7739
7740         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7741         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7742         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7743
7744         assert_eq!(revoked_htlc_txn[2].input.len(), 1);
7745         assert_eq!(revoked_htlc_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7746         assert_eq!(revoked_htlc_txn[2].output.len(), 1);
7747         check_spends!(revoked_htlc_txn[2], revoked_local_txn[0]);
7748
7749         // Broadcast set of revoked txn on A
7750         let hash_128 = connect_blocks(&nodes[0], 40);
7751         let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7752         connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] });
7753         let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7754         connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[2].clone()] });
7755         let events = nodes[0].node.get_and_clear_pending_events();
7756         expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7757         match events.last().unwrap() {
7758                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7759                 _ => panic!("Unexpected event"),
7760         }
7761         let first;
7762         let feerate_1;
7763         let penalty_txn;
7764         {
7765                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7766                 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7767                 // Verify claim tx are spending revoked HTLC txn
7768
7769                 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7770                 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7771                 // which are included in the same block (they are broadcasted because we scan the
7772                 // transactions linearly and generate claims as we go, they likely should be removed in the
7773                 // future).
7774                 assert_eq!(node_txn[0].input.len(), 1);
7775                 check_spends!(node_txn[0], revoked_local_txn[0]);
7776                 assert_eq!(node_txn[1].input.len(), 1);
7777                 check_spends!(node_txn[1], revoked_local_txn[0]);
7778                 assert_eq!(node_txn[2].input.len(), 1);
7779                 check_spends!(node_txn[2], revoked_local_txn[0]);
7780
7781                 // Each of the three justice transactions claim a separate (single) output of the three
7782                 // available, which we check here:
7783                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7784                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7785                 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7786
7787                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7788                 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7789
7790                 // node_txn[3] is the local commitment tx broadcast just because (and somewhat in case of
7791                 // reorgs, though its not clear its ever worth broadcasting conflicting txn like this when
7792                 // a remote commitment tx has already been confirmed).
7793                 check_spends!(node_txn[3], chan.3);
7794
7795                 // node_txn[4] spends the revoked outputs from the revoked_htlc_txn (which only have one
7796                 // output, checked above).
7797                 assert_eq!(node_txn[4].input.len(), 2);
7798                 assert_eq!(node_txn[4].output.len(), 1);
7799                 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7800
7801                 first = node_txn[4].txid();
7802                 // Store both feerates for later comparison
7803                 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[4].output[0].value;
7804                 feerate_1 = fee_1 * 1000 / node_txn[4].weight() as u64;
7805                 penalty_txn = vec![node_txn[2].clone()];
7806                 node_txn.clear();
7807         }
7808
7809         // Connect one more block to see if bumped penalty are issued for HTLC txn
7810         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7811         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7812         let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7813         connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() });
7814
7815         // Few more blocks to confirm penalty txn
7816         connect_blocks(&nodes[0], 4);
7817         assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7818         let header_144 = connect_blocks(&nodes[0], 9);
7819         let node_txn = {
7820                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7821                 assert_eq!(node_txn.len(), 1);
7822
7823                 assert_eq!(node_txn[0].input.len(), 2);
7824                 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7825                 // Verify bumped tx is different and 25% bump heuristic
7826                 assert_ne!(first, node_txn[0].txid());
7827                 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[0].output[0].value;
7828                 let feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7829                 assert!(feerate_2 * 100 > feerate_1 * 125);
7830                 let txn = vec![node_txn[0].clone()];
7831                 node_txn.clear();
7832                 txn
7833         };
7834         // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7835         let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7836         connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn });
7837         connect_blocks(&nodes[0], 20);
7838         {
7839                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7840                 // We verify than no new transaction has been broadcast because previously
7841                 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7842                 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7843                 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7844                 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7845                 // up bumped justice generation.
7846                 assert_eq!(node_txn.len(), 0);
7847                 node_txn.clear();
7848         }
7849         check_closed_broadcast!(nodes[0], true);
7850         check_added_monitors!(nodes[0], 1);
7851 }
7852
7853 #[test]
7854 fn test_bump_penalty_txn_on_remote_commitment() {
7855         // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7856         // we're able to claim outputs on remote commitment transaction before timelocks expiration
7857
7858         // Create 2 HTLCs
7859         // Provide preimage for one
7860         // Check aggregation
7861
7862         let chanmon_cfgs = create_chanmon_cfgs(2);
7863         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7864         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7865         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7866
7867         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7868         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
7869         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7870
7871         // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7872         let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7873         assert_eq!(remote_txn[0].output.len(), 4);
7874         assert_eq!(remote_txn[0].input.len(), 1);
7875         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7876
7877         // Claim a HTLC without revocation (provide B monitor with preimage)
7878         nodes[1].node.claim_funds(payment_preimage);
7879         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
7880         mine_transaction(&nodes[1], &remote_txn[0]);
7881         check_added_monitors!(nodes[1], 2);
7882         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7883
7884         // One or more claim tx should have been broadcast, check it
7885         let timeout;
7886         let preimage;
7887         let preimage_bump;
7888         let feerate_timeout;
7889         let feerate_preimage;
7890         {
7891                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7892                 // 5 transactions including:
7893                 //   local commitment + HTLC-Success
7894                 //   preimage and timeout sweeps from remote commitment + preimage sweep bump
7895                 assert_eq!(node_txn.len(), 5);
7896                 assert_eq!(node_txn[0].input.len(), 1);
7897                 assert_eq!(node_txn[3].input.len(), 1);
7898                 assert_eq!(node_txn[4].input.len(), 1);
7899                 check_spends!(node_txn[0], remote_txn[0]);
7900                 check_spends!(node_txn[3], remote_txn[0]);
7901                 check_spends!(node_txn[4], remote_txn[0]);
7902
7903                 check_spends!(node_txn[1], chan.3); // local commitment
7904                 check_spends!(node_txn[2], node_txn[1]); // local HTLC-Success
7905
7906                 preimage = node_txn[0].txid();
7907                 let index = node_txn[0].input[0].previous_output.vout;
7908                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7909                 feerate_preimage = fee * 1000 / node_txn[0].weight() as u64;
7910
7911                 let (preimage_bump_tx, timeout_tx) = if node_txn[3].input[0].previous_output == node_txn[0].input[0].previous_output {
7912                         (node_txn[3].clone(), node_txn[4].clone())
7913                 } else {
7914                         (node_txn[4].clone(), node_txn[3].clone())
7915                 };
7916
7917                 preimage_bump = preimage_bump_tx;
7918                 check_spends!(preimage_bump, remote_txn[0]);
7919                 assert_eq!(node_txn[0].input[0].previous_output, preimage_bump.input[0].previous_output);
7920
7921                 timeout = timeout_tx.txid();
7922                 let index = timeout_tx.input[0].previous_output.vout;
7923                 let fee = remote_txn[0].output[index as usize].value - timeout_tx.output[0].value;
7924                 feerate_timeout = fee * 1000 / timeout_tx.weight() as u64;
7925
7926                 node_txn.clear();
7927         };
7928         assert_ne!(feerate_timeout, 0);
7929         assert_ne!(feerate_preimage, 0);
7930
7931         // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7932         connect_blocks(&nodes[1], 15);
7933         {
7934                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7935                 assert_eq!(node_txn.len(), 1);
7936                 assert_eq!(node_txn[0].input.len(), 1);
7937                 assert_eq!(preimage_bump.input.len(), 1);
7938                 check_spends!(node_txn[0], remote_txn[0]);
7939                 check_spends!(preimage_bump, remote_txn[0]);
7940
7941                 let index = preimage_bump.input[0].previous_output.vout;
7942                 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
7943                 let new_feerate = fee * 1000 / preimage_bump.weight() as u64;
7944                 assert!(new_feerate * 100 > feerate_timeout * 125);
7945                 assert_ne!(timeout, preimage_bump.txid());
7946
7947                 let index = node_txn[0].input[0].previous_output.vout;
7948                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7949                 let new_feerate = fee * 1000 / node_txn[0].weight() as u64;
7950                 assert!(new_feerate * 100 > feerate_preimage * 125);
7951                 assert_ne!(preimage, node_txn[0].txid());
7952
7953                 node_txn.clear();
7954         }
7955
7956         nodes[1].node.get_and_clear_pending_events();
7957         nodes[1].node.get_and_clear_pending_msg_events();
7958 }
7959
7960 #[test]
7961 fn test_counterparty_raa_skip_no_crash() {
7962         // Previously, if our counterparty sent two RAAs in a row without us having provided a
7963         // commitment transaction, we would have happily carried on and provided them the next
7964         // commitment transaction based on one RAA forward. This would probably eventually have led to
7965         // channel closure, but it would not have resulted in funds loss. Still, our
7966         // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
7967         // check simply that the channel is closed in response to such an RAA, but don't check whether
7968         // we decide to punish our counterparty for revoking their funds (as we don't currently
7969         // implement that).
7970         let chanmon_cfgs = create_chanmon_cfgs(2);
7971         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7972         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7973         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7974         let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
7975
7976         let per_commitment_secret;
7977         let next_per_commitment_point;
7978         {
7979                 let mut guard = nodes[0].node.channel_state.lock().unwrap();
7980                 let keys = guard.by_id.get_mut(&channel_id).unwrap().get_signer();
7981
7982                 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7983
7984                 // Make signer believe we got a counterparty signature, so that it allows the revocation
7985                 keys.get_enforcement_state().last_holder_commitment -= 1;
7986                 per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
7987
7988                 // Must revoke without gaps
7989                 keys.get_enforcement_state().last_holder_commitment -= 1;
7990                 keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
7991
7992                 keys.get_enforcement_state().last_holder_commitment -= 1;
7993                 next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7994                         &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7995         }
7996
7997         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7998                 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
7999         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
8000         check_added_monitors!(nodes[1], 1);
8001         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
8002 }
8003
8004 #[test]
8005 fn test_bump_txn_sanitize_tracking_maps() {
8006         // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
8007         // verify we clean then right after expiration of ANTI_REORG_DELAY.
8008
8009         let chanmon_cfgs = create_chanmon_cfgs(2);
8010         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8011         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8012         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8013
8014         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8015         // Lock HTLC in both directions
8016         let (payment_preimage_1, _, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000);
8017         let (_, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000);
8018
8019         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
8020         assert_eq!(revoked_local_txn[0].input.len(), 1);
8021         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8022
8023         // Revoke local commitment tx
8024         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
8025
8026         // Broadcast set of revoked txn on A
8027         connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
8028         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[0], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
8029         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
8030
8031         mine_transaction(&nodes[0], &revoked_local_txn[0]);
8032         check_closed_broadcast!(nodes[0], true);
8033         check_added_monitors!(nodes[0], 1);
8034         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8035         let penalty_txn = {
8036                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8037                 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
8038                 check_spends!(node_txn[0], revoked_local_txn[0]);
8039                 check_spends!(node_txn[1], revoked_local_txn[0]);
8040                 check_spends!(node_txn[2], revoked_local_txn[0]);
8041                 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
8042                 node_txn.clear();
8043                 penalty_txn
8044         };
8045         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8046         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
8047         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8048         {
8049                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
8050                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
8051                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
8052         }
8053 }
8054
8055 #[test]
8056 fn test_pending_claimed_htlc_no_balance_underflow() {
8057         // Tests that if we have a pending outbound HTLC as well as a claimed-but-not-fully-removed
8058         // HTLC we will not underflow when we call `Channel::get_balance_msat()`.
8059         let chanmon_cfgs = create_chanmon_cfgs(2);
8060         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8061         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8062         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8063         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8064
8065         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_010_000);
8066         nodes[1].node.claim_funds(payment_preimage);
8067         expect_payment_claimed!(nodes[1], payment_hash, 1_010_000);
8068         check_added_monitors!(nodes[1], 1);
8069         let fulfill_ev = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8070
8071         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &fulfill_ev.update_fulfill_htlcs[0]);
8072         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
8073         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &fulfill_ev.commitment_signed);
8074         check_added_monitors!(nodes[0], 1);
8075         let (_raa, _cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
8076
8077         // At this point nodes[1] has received 1,010k msat (10k msat more than their reserve) and can
8078         // send an HTLC back (though it will go in the holding cell). Send an HTLC back and check we
8079         // can get our balance.
8080
8081         // Get a route from nodes[1] to nodes[0] by getting a route going the other way and then flip
8082         // the public key of the only hop. This works around ChannelDetails not showing the
8083         // almost-claimed HTLC as available balance.
8084         let (mut route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 10_000);
8085         route.payment_params = None; // This is all wrong, but unnecessary
8086         route.paths[0][0].pubkey = nodes[0].node.get_our_node_id();
8087         let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[0]);
8088         nodes[1].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
8089
8090         assert_eq!(nodes[1].node.list_channels()[0].balance_msat, 1_000_000);
8091 }
8092
8093 #[test]
8094 fn test_channel_conf_timeout() {
8095         // Tests that, for inbound channels, we give up on them if the funding transaction does not
8096         // confirm within 2016 blocks, as recommended by BOLT 2.
8097         let chanmon_cfgs = create_chanmon_cfgs(2);
8098         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8099         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8100         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8101
8102         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());
8103
8104         // The outbound node should wait forever for confirmation:
8105         // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
8106         // copied here instead of directly referencing the constant.
8107         connect_blocks(&nodes[0], 2016);
8108         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8109
8110         // The inbound node should fail the channel after exactly 2016 blocks
8111         connect_blocks(&nodes[1], 2015);
8112         check_added_monitors!(nodes[1], 0);
8113         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8114
8115         connect_blocks(&nodes[1], 1);
8116         check_added_monitors!(nodes[1], 1);
8117         check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut);
8118         let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
8119         assert_eq!(close_ev.len(), 1);
8120         match close_ev[0] {
8121                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
8122                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8123                         assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
8124                 },
8125                 _ => panic!("Unexpected event"),
8126         }
8127 }
8128
8129 #[test]
8130 fn test_override_channel_config() {
8131         let chanmon_cfgs = create_chanmon_cfgs(2);
8132         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8133         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8134         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8135
8136         // Node0 initiates a channel to node1 using the override config.
8137         let mut override_config = UserConfig::default();
8138         override_config.channel_handshake_config.our_to_self_delay = 200;
8139
8140         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
8141
8142         // Assert the channel created by node0 is using the override config.
8143         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8144         assert_eq!(res.channel_flags, 0);
8145         assert_eq!(res.to_self_delay, 200);
8146 }
8147
8148 #[test]
8149 fn test_override_0msat_htlc_minimum() {
8150         let mut zero_config = UserConfig::default();
8151         zero_config.channel_handshake_config.our_htlc_minimum_msat = 0;
8152         let chanmon_cfgs = create_chanmon_cfgs(2);
8153         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8154         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
8155         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8156
8157         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
8158         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8159         assert_eq!(res.htlc_minimum_msat, 1);
8160
8161         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &res);
8162         let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8163         assert_eq!(res.htlc_minimum_msat, 1);
8164 }
8165
8166 #[test]
8167 fn test_channel_update_has_correct_htlc_maximum_msat() {
8168         // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
8169         // Bolt 7 specifies that if present `htlc_maximum_msat`:
8170         // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
8171         // 90% of the `channel_value`.
8172         // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
8173
8174         let mut config_30_percent = UserConfig::default();
8175         config_30_percent.channel_handshake_config.announced_channel = true;
8176         config_30_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
8177         let mut config_50_percent = UserConfig::default();
8178         config_50_percent.channel_handshake_config.announced_channel = true;
8179         config_50_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
8180         let mut config_95_percent = UserConfig::default();
8181         config_95_percent.channel_handshake_config.announced_channel = true;
8182         config_95_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
8183         let mut config_100_percent = UserConfig::default();
8184         config_100_percent.channel_handshake_config.announced_channel = true;
8185         config_100_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
8186
8187         let chanmon_cfgs = create_chanmon_cfgs(4);
8188         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8189         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)]);
8190         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8191
8192         let channel_value_satoshis = 100000;
8193         let channel_value_msat = channel_value_satoshis * 1000;
8194         let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
8195         let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
8196         let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
8197
8198         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());
8199         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());
8200
8201         // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
8202         // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
8203         assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, channel_value_50_percent_msat);
8204         // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
8205         // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
8206         assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, channel_value_30_percent_msat);
8207
8208         // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
8209         // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
8210         // `channel_value`.
8211         assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
8212         // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
8213         // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
8214         // `channel_value`.
8215         assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
8216 }
8217
8218 #[test]
8219 fn test_manually_accept_inbound_channel_request() {
8220         let mut manually_accept_conf = UserConfig::default();
8221         manually_accept_conf.manually_accept_inbound_channels = true;
8222         let chanmon_cfgs = create_chanmon_cfgs(2);
8223         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8224         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8225         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8226
8227         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8228         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8229
8230         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &res);
8231
8232         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8233         // accepting the inbound channel request.
8234         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8235
8236         let events = nodes[1].node.get_and_clear_pending_events();
8237         match events[0] {
8238                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8239                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
8240                 }
8241                 _ => panic!("Unexpected event"),
8242         }
8243
8244         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8245         assert_eq!(accept_msg_ev.len(), 1);
8246
8247         match accept_msg_ev[0] {
8248                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8249                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8250                 }
8251                 _ => panic!("Unexpected event"),
8252         }
8253
8254         nodes[1].node.force_close_broadcasting_latest_txn(&temp_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
8255
8256         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8257         assert_eq!(close_msg_ev.len(), 1);
8258
8259         let events = nodes[1].node.get_and_clear_pending_events();
8260         match events[0] {
8261                 Event::ChannelClosed { user_channel_id, .. } => {
8262                         assert_eq!(user_channel_id, 23);
8263                 }
8264                 _ => panic!("Unexpected event"),
8265         }
8266 }
8267
8268 #[test]
8269 fn test_manually_reject_inbound_channel_request() {
8270         let mut manually_accept_conf = UserConfig::default();
8271         manually_accept_conf.manually_accept_inbound_channels = true;
8272         let chanmon_cfgs = create_chanmon_cfgs(2);
8273         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8274         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8275         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8276
8277         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8278         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8279
8280         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &res);
8281
8282         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8283         // rejecting the inbound channel request.
8284         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8285
8286         let events = nodes[1].node.get_and_clear_pending_events();
8287         match events[0] {
8288                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8289                         nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
8290                 }
8291                 _ => panic!("Unexpected event"),
8292         }
8293
8294         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8295         assert_eq!(close_msg_ev.len(), 1);
8296
8297         match close_msg_ev[0] {
8298                 MessageSendEvent::HandleError { ref node_id, .. } => {
8299                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8300                 }
8301                 _ => panic!("Unexpected event"),
8302         }
8303         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
8304 }
8305
8306 #[test]
8307 fn test_reject_funding_before_inbound_channel_accepted() {
8308         // This tests that when `UserConfig::manually_accept_inbound_channels` is set to true, inbound
8309         // channels must to be manually accepted through `ChannelManager::accept_inbound_channel` by
8310         // the node operator before the counterparty sends a `FundingCreated` message. If a
8311         // `FundingCreated` message is received before the channel is accepted, it should be rejected
8312         // and the channel should be closed.
8313         let mut manually_accept_conf = UserConfig::default();
8314         manually_accept_conf.manually_accept_inbound_channels = true;
8315         let chanmon_cfgs = create_chanmon_cfgs(2);
8316         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8317         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8318         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8319
8320         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8321         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8322         let temp_channel_id = res.temporary_channel_id;
8323
8324         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &res);
8325
8326         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in the `msg_events`.
8327         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8328
8329         // Clear the `Event::OpenChannelRequest` event without responding to the request.
8330         nodes[1].node.get_and_clear_pending_events();
8331
8332         // Get the `AcceptChannel` message of `nodes[1]` without calling
8333         // `ChannelManager::accept_inbound_channel`, which generates a
8334         // `MessageSendEvent::SendAcceptChannel` event. The message is passed to `nodes[0]`
8335         // `handle_accept_channel`, which is required in order for `create_funding_transaction` to
8336         // succeed when `nodes[0]` is passed to it.
8337         let accept_chan_msg = {
8338                 let mut lock;
8339                 let channel = get_channel_ref!(&nodes[1], lock, temp_channel_id);
8340                 channel.get_accept_channel_message()
8341         };
8342         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_chan_msg);
8343
8344         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8345
8346         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8347         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8348
8349         // The `funding_created_msg` should be rejected by `nodes[1]` as it hasn't accepted the channel
8350         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8351
8352         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8353         assert_eq!(close_msg_ev.len(), 1);
8354
8355         let expected_err = "FundingCreated message received before the channel was accepted";
8356         match close_msg_ev[0] {
8357                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id, } => {
8358                         assert_eq!(msg.channel_id, temp_channel_id);
8359                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8360                         assert_eq!(msg.data, expected_err);
8361                 }
8362                 _ => panic!("Unexpected event"),
8363         }
8364
8365         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
8366 }
8367
8368 #[test]
8369 fn test_can_not_accept_inbound_channel_twice() {
8370         let mut manually_accept_conf = UserConfig::default();
8371         manually_accept_conf.manually_accept_inbound_channels = true;
8372         let chanmon_cfgs = create_chanmon_cfgs(2);
8373         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8374         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8375         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8376
8377         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8378         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8379
8380         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &res);
8381
8382         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8383         // accepting the inbound channel request.
8384         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8385
8386         let events = nodes[1].node.get_and_clear_pending_events();
8387         match events[0] {
8388                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8389                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
8390                         let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
8391                         match api_res {
8392                                 Err(APIError::APIMisuseError { err }) => {
8393                                         assert_eq!(err, "The channel isn't currently awaiting to be accepted.");
8394                                 },
8395                                 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
8396                                 Err(_) => panic!("Unexpected Error"),
8397                         }
8398                 }
8399                 _ => panic!("Unexpected event"),
8400         }
8401
8402         // Ensure that the channel wasn't closed after attempting to accept it twice.
8403         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8404         assert_eq!(accept_msg_ev.len(), 1);
8405
8406         match accept_msg_ev[0] {
8407                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8408                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8409                 }
8410                 _ => panic!("Unexpected event"),
8411         }
8412 }
8413
8414 #[test]
8415 fn test_can_not_accept_unknown_inbound_channel() {
8416         let chanmon_cfg = create_chanmon_cfgs(2);
8417         let node_cfg = create_node_cfgs(2, &chanmon_cfg);
8418         let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
8419         let nodes = create_network(2, &node_cfg, &node_chanmgr);
8420
8421         let unknown_channel_id = [0; 32];
8422         let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
8423         match api_res {
8424                 Err(APIError::ChannelUnavailable { err }) => {
8425                         assert_eq!(err, "Can't accept a channel that doesn't exist");
8426                 },
8427                 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
8428                 Err(_) => panic!("Unexpected Error"),
8429         }
8430 }
8431
8432 #[test]
8433 fn test_simple_mpp() {
8434         // Simple test of sending a multi-path payment.
8435         let chanmon_cfgs = create_chanmon_cfgs(4);
8436         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8437         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8438         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8439
8440         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;
8441         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;
8442         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;
8443         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;
8444
8445         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8446         let path = route.paths[0].clone();
8447         route.paths.push(path);
8448         route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8449         route.paths[0][0].short_channel_id = chan_1_id;
8450         route.paths[0][1].short_channel_id = chan_3_id;
8451         route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8452         route.paths[1][0].short_channel_id = chan_2_id;
8453         route.paths[1][1].short_channel_id = chan_4_id;
8454         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8455         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8456 }
8457
8458 #[test]
8459 fn test_preimage_storage() {
8460         // Simple test of payment preimage storage allowing no client-side storage to claim payments
8461         let chanmon_cfgs = create_chanmon_cfgs(2);
8462         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8463         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8464         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8465
8466         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).0.contents.short_channel_id;
8467
8468         {
8469                 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200).unwrap();
8470                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8471                 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
8472                 check_added_monitors!(nodes[0], 1);
8473                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8474                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8475                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8476                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8477         }
8478         // Note that after leaving the above scope we have no knowledge of any arguments or return
8479         // values from previous calls.
8480         expect_pending_htlcs_forwardable!(nodes[1]);
8481         let events = nodes[1].node.get_and_clear_pending_events();
8482         assert_eq!(events.len(), 1);
8483         match events[0] {
8484                 Event::PaymentReceived { ref purpose, .. } => {
8485                         match &purpose {
8486                                 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
8487                                         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8488                                 },
8489                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
8490                         }
8491                 },
8492                 _ => panic!("Unexpected event"),
8493         }
8494 }
8495
8496 #[test]
8497 #[allow(deprecated)]
8498 fn test_secret_timeout() {
8499         // Simple test of payment secret storage time outs. After
8500         // `create_inbound_payment(_for_hash)_legacy` is removed, this test will be removed as well.
8501         let chanmon_cfgs = create_chanmon_cfgs(2);
8502         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8503         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8504         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8505
8506         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).0.contents.short_channel_id;
8507
8508         let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment_legacy(Some(100_000), 2).unwrap();
8509
8510         // We should fail to register the same payment hash twice, at least until we've connected a
8511         // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
8512         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8513                 assert_eq!(err, "Duplicate payment hash");
8514         } else { panic!(); }
8515         let mut block = {
8516                 let node_1_blocks = nodes[1].blocks.lock().unwrap();
8517                 Block {
8518                         header: BlockHeader {
8519                                 version: 0x2000000,
8520                                 prev_blockhash: node_1_blocks.last().unwrap().0.block_hash(),
8521                                 merkle_root: TxMerkleNode::all_zeros(),
8522                                 time: node_1_blocks.len() as u32 + 7200, bits: 42, nonce: 42 },
8523                         txdata: vec![],
8524                 }
8525         };
8526         connect_block(&nodes[1], &block);
8527         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8528                 assert_eq!(err, "Duplicate payment hash");
8529         } else { panic!(); }
8530
8531         // If we then connect the second block, we should be able to register the same payment hash
8532         // again (this time getting a new payment secret).
8533         block.header.prev_blockhash = block.header.block_hash();
8534         block.header.time += 1;
8535         connect_block(&nodes[1], &block);
8536         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2).unwrap();
8537         assert_ne!(payment_secret_1, our_payment_secret);
8538
8539         {
8540                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8541                 nodes[0].node.send_payment(&route, payment_hash, &Some(our_payment_secret), PaymentId(payment_hash.0)).unwrap();
8542                 check_added_monitors!(nodes[0], 1);
8543                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8544                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8545                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8546                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8547         }
8548         // Note that after leaving the above scope we have no knowledge of any arguments or return
8549         // values from previous calls.
8550         expect_pending_htlcs_forwardable!(nodes[1]);
8551         let events = nodes[1].node.get_and_clear_pending_events();
8552         assert_eq!(events.len(), 1);
8553         match events[0] {
8554                 Event::PaymentReceived { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret }, .. } => {
8555                         assert!(payment_preimage.is_none());
8556                         assert_eq!(payment_secret, our_payment_secret);
8557                         // We don't actually have the payment preimage with which to claim this payment!
8558                 },
8559                 _ => panic!("Unexpected event"),
8560         }
8561 }
8562
8563 #[test]
8564 fn test_bad_secret_hash() {
8565         // Simple test of unregistered payment hash/invalid payment secret handling
8566         let chanmon_cfgs = create_chanmon_cfgs(2);
8567         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8568         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8569         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8570
8571         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).0.contents.short_channel_id;
8572
8573         let random_payment_hash = PaymentHash([42; 32]);
8574         let random_payment_secret = PaymentSecret([43; 32]);
8575         let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2).unwrap();
8576         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8577
8578         // All the below cases should end up being handled exactly identically, so we macro the
8579         // resulting events.
8580         macro_rules! handle_unknown_invalid_payment_data {
8581                 ($payment_hash: expr) => {
8582                         check_added_monitors!(nodes[0], 1);
8583                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8584                         let payment_event = SendEvent::from_event(events.pop().unwrap());
8585                         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8586                         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8587
8588                         // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8589                         // again to process the pending backwards-failure of the HTLC
8590                         expect_pending_htlcs_forwardable!(nodes[1]);
8591                         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment{ payment_hash: $payment_hash }]);
8592                         check_added_monitors!(nodes[1], 1);
8593
8594                         // We should fail the payment back
8595                         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8596                         match events.pop().unwrap() {
8597                                 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8598                                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8599                                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8600                                 },
8601                                 _ => panic!("Unexpected event"),
8602                         }
8603                 }
8604         }
8605
8606         let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8607         // Error data is the HTLC value (100,000) and current block height
8608         let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8609
8610         // Send a payment with the right payment hash but the wrong payment secret
8611         nodes[0].node.send_payment(&route, our_payment_hash, &Some(random_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
8612         handle_unknown_invalid_payment_data!(our_payment_hash);
8613         expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8614
8615         // Send a payment with a random payment hash, but the right payment secret
8616         nodes[0].node.send_payment(&route, random_payment_hash, &Some(our_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8617         handle_unknown_invalid_payment_data!(random_payment_hash);
8618         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8619
8620         // Send a payment with a random payment hash and random payment secret
8621         nodes[0].node.send_payment(&route, random_payment_hash, &Some(random_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8622         handle_unknown_invalid_payment_data!(random_payment_hash);
8623         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8624 }
8625
8626 #[test]
8627 fn test_update_err_monitor_lockdown() {
8628         // Our monitor will lock update of local commitment transaction if a broadcastion condition
8629         // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8630         // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateStatus
8631         // error.
8632         //
8633         // This scenario may happen in a watchtower setup, where watchtower process a block height
8634         // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8635         // commitment at same time.
8636
8637         let chanmon_cfgs = create_chanmon_cfgs(2);
8638         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8639         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8640         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8641
8642         // Create some initial channel
8643         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8644         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8645
8646         // Rebalance the network to generate htlc in the two directions
8647         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8648
8649         // Route a HTLC from node 0 to node 1 (but don't settle)
8650         let (preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
8651
8652         // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8653         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8654         let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8655         let persister = test_utils::TestPersister::new();
8656         let watchtower = {
8657                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8658                 let mut w = test_utils::TestVecWriter(Vec::new());
8659                 monitor.write(&mut w).unwrap();
8660                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8661                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8662                 assert!(new_monitor == *monitor);
8663                 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);
8664                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8665                 watchtower
8666         };
8667         let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8668         let block = Block { header, txdata: vec![] };
8669         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8670         // transaction lock time requirements here.
8671         chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 0));
8672         watchtower.chain_monitor.block_connected(&block, 200);
8673
8674         // Try to update ChannelMonitor
8675         nodes[1].node.claim_funds(preimage);
8676         check_added_monitors!(nodes[1], 1);
8677         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
8678
8679         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8680         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8681         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8682         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8683                 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8684                         assert_eq!(watchtower.chain_monitor.update_channel(outpoint, update.clone()), ChannelMonitorUpdateStatus::PermanentFailure);
8685                         assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, update), ChannelMonitorUpdateStatus::Completed);
8686                 } else { assert!(false); }
8687         } else { assert!(false); };
8688         // Our local monitor is in-sync and hasn't processed yet timeout
8689         check_added_monitors!(nodes[0], 1);
8690         let events = nodes[0].node.get_and_clear_pending_events();
8691         assert_eq!(events.len(), 1);
8692 }
8693
8694 #[test]
8695 fn test_concurrent_monitor_claim() {
8696         // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8697         // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8698         // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8699         // state N+1 confirms. Alice claims output from state N+1.
8700
8701         let chanmon_cfgs = create_chanmon_cfgs(2);
8702         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8703         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8704         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8705
8706         // Create some initial channel
8707         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8708         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8709
8710         // Rebalance the network to generate htlc in the two directions
8711         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8712
8713         // Route a HTLC from node 0 to node 1 (but don't settle)
8714         route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8715
8716         // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8717         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8718         let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8719         let persister = test_utils::TestPersister::new();
8720         let watchtower_alice = {
8721                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8722                 let mut w = test_utils::TestVecWriter(Vec::new());
8723                 monitor.write(&mut w).unwrap();
8724                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8725                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8726                 assert!(new_monitor == *monitor);
8727                 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);
8728                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8729                 watchtower
8730         };
8731         let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8732         let block = Block { header, txdata: vec![] };
8733         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8734         // transaction lock time requirements here.
8735         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));
8736         watchtower_alice.chain_monitor.block_connected(&block, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8737
8738         // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8739         {
8740                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8741                 assert_eq!(txn.len(), 2);
8742                 txn.clear();
8743         }
8744
8745         // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8746         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8747         let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8748         let persister = test_utils::TestPersister::new();
8749         let watchtower_bob = {
8750                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8751                 let mut w = test_utils::TestVecWriter(Vec::new());
8752                 monitor.write(&mut w).unwrap();
8753                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8754                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8755                 assert!(new_monitor == *monitor);
8756                 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);
8757                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8758                 watchtower
8759         };
8760         let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8761         watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8762
8763         // Route another payment to generate another update with still previous HTLC pending
8764         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8765         {
8766                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
8767         }
8768         check_added_monitors!(nodes[1], 1);
8769
8770         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8771         assert_eq!(updates.update_add_htlcs.len(), 1);
8772         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8773         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8774                 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8775                         // Watchtower Alice should already have seen the block and reject the update
8776                         assert_eq!(watchtower_alice.chain_monitor.update_channel(outpoint, update.clone()), ChannelMonitorUpdateStatus::PermanentFailure);
8777                         assert_eq!(watchtower_bob.chain_monitor.update_channel(outpoint, update.clone()), ChannelMonitorUpdateStatus::Completed);
8778                         assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, update), ChannelMonitorUpdateStatus::Completed);
8779                 } else { assert!(false); }
8780         } else { assert!(false); };
8781         // Our local monitor is in-sync and hasn't processed yet timeout
8782         check_added_monitors!(nodes[0], 1);
8783
8784         //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8785         let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8786         watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8787
8788         // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8789         let bob_state_y;
8790         {
8791                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8792                 assert_eq!(txn.len(), 2);
8793                 bob_state_y = txn[0].clone();
8794                 txn.clear();
8795         };
8796
8797         // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8798         let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8799         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);
8800         {
8801                 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8802                 assert_eq!(htlc_txn.len(), 1);
8803                 check_spends!(htlc_txn[0], bob_state_y);
8804         }
8805 }
8806
8807 #[test]
8808 fn test_pre_lockin_no_chan_closed_update() {
8809         // Test that if a peer closes a channel in response to a funding_created message we don't
8810         // generate a channel update (as the channel cannot appear on chain without a funding_signed
8811         // message).
8812         //
8813         // Doing so would imply a channel monitor update before the initial channel monitor
8814         // registration, violating our API guarantees.
8815         //
8816         // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8817         // then opening a second channel with the same funding output as the first (which is not
8818         // rejected because the first channel does not exist in the ChannelManager) and closing it
8819         // before receiving funding_signed.
8820         let chanmon_cfgs = create_chanmon_cfgs(2);
8821         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8822         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8823         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8824
8825         // Create an initial channel
8826         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8827         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8828         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_chan_msg);
8829         let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8830         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_chan_msg);
8831
8832         // Move the first channel through the funding flow...
8833         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8834
8835         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8836         check_added_monitors!(nodes[0], 0);
8837
8838         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8839         let channel_id = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8840         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8841         assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8842         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "Hi".to_string() }, true);
8843 }
8844
8845 #[test]
8846 fn test_htlc_no_detection() {
8847         // This test is a mutation to underscore the detection logic bug we had
8848         // before #653. HTLC value routed is above the remaining balance, thus
8849         // inverting HTLC and `to_remote` output. HTLC will come second and
8850         // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8851         // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8852         // outputs order detection for correct spending children filtring.
8853
8854         let chanmon_cfgs = create_chanmon_cfgs(2);
8855         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8856         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8857         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8858
8859         // Create some initial channels
8860         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8861
8862         send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8863         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8864         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8865         assert_eq!(local_txn[0].input.len(), 1);
8866         assert_eq!(local_txn[0].output.len(), 3);
8867         check_spends!(local_txn[0], chan_1.3);
8868
8869         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8870         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8871         connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] });
8872         // We deliberately connect the local tx twice as this should provoke a failure calling
8873         // this test before #653 fix.
8874         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);
8875         check_closed_broadcast!(nodes[0], true);
8876         check_added_monitors!(nodes[0], 1);
8877         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8878         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1);
8879
8880         let htlc_timeout = {
8881                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8882                 assert_eq!(node_txn[1].input.len(), 1);
8883                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8884                 check_spends!(node_txn[1], local_txn[0]);
8885                 node_txn[1].clone()
8886         };
8887
8888         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8889         connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] });
8890         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8891         expect_payment_failed!(nodes[0], our_payment_hash, false);
8892 }
8893
8894 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8895         // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8896         // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8897         // Carol, Alice would be the upstream node, and Carol the downstream.)
8898         //
8899         // Steps of the test:
8900         // 1) Alice sends a HTLC to Carol through Bob.
8901         // 2) Carol doesn't settle the HTLC.
8902         // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8903         // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8904         // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8905         //    but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8906         // 5) Carol release the preimage to Bob off-chain.
8907         // 6) Bob claims the offered output on the broadcasted commitment.
8908         let chanmon_cfgs = create_chanmon_cfgs(3);
8909         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8910         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8911         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8912
8913         // Create some initial channels
8914         let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8915         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8916
8917         // Steps (1) and (2):
8918         // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8919         let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
8920
8921         // Check that Alice's commitment transaction now contains an output for this HTLC.
8922         let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8923         check_spends!(alice_txn[0], chan_ab.3);
8924         assert_eq!(alice_txn[0].output.len(), 2);
8925         check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8926         assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8927         assert_eq!(alice_txn.len(), 2);
8928
8929         // Steps (3) and (4):
8930         // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8931         // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8932         let mut force_closing_node = 0; // Alice force-closes
8933         let mut counterparty_node = 1; // Bob if Alice force-closes
8934
8935         // Bob force-closes
8936         if !broadcast_alice {
8937                 force_closing_node = 1;
8938                 counterparty_node = 0;
8939         }
8940         nodes[force_closing_node].node.force_close_broadcasting_latest_txn(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id()).unwrap();
8941         check_closed_broadcast!(nodes[force_closing_node], true);
8942         check_added_monitors!(nodes[force_closing_node], 1);
8943         check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
8944         if go_onchain_before_fulfill {
8945                 let txn_to_broadcast = match broadcast_alice {
8946                         true => alice_txn.clone(),
8947                         false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8948                 };
8949                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
8950                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8951                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8952                 if broadcast_alice {
8953                         check_closed_broadcast!(nodes[1], true);
8954                         check_added_monitors!(nodes[1], 1);
8955                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8956                 }
8957                 assert_eq!(bob_txn.len(), 1);
8958                 check_spends!(bob_txn[0], chan_ab.3);
8959         }
8960
8961         // Step (5):
8962         // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8963         // process of removing the HTLC from their commitment transactions.
8964         nodes[2].node.claim_funds(payment_preimage);
8965         check_added_monitors!(nodes[2], 1);
8966         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
8967
8968         let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8969         assert!(carol_updates.update_add_htlcs.is_empty());
8970         assert!(carol_updates.update_fail_htlcs.is_empty());
8971         assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8972         assert!(carol_updates.update_fee.is_none());
8973         assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8974
8975         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8976         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false, false);
8977         // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8978         if !go_onchain_before_fulfill && broadcast_alice {
8979                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8980                 assert_eq!(events.len(), 1);
8981                 match events[0] {
8982                         MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8983                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8984                         },
8985                         _ => panic!("Unexpected event"),
8986                 };
8987         }
8988         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8989         // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8990         // Carol<->Bob's updated commitment transaction info.
8991         check_added_monitors!(nodes[1], 2);
8992
8993         let events = nodes[1].node.get_and_clear_pending_msg_events();
8994         assert_eq!(events.len(), 2);
8995         let bob_revocation = match events[0] {
8996                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8997                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8998                         (*msg).clone()
8999                 },
9000                 _ => panic!("Unexpected event"),
9001         };
9002         let bob_updates = match events[1] {
9003                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
9004                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
9005                         (*updates).clone()
9006                 },
9007                 _ => panic!("Unexpected event"),
9008         };
9009
9010         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
9011         check_added_monitors!(nodes[2], 1);
9012         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
9013         check_added_monitors!(nodes[2], 1);
9014
9015         let events = nodes[2].node.get_and_clear_pending_msg_events();
9016         assert_eq!(events.len(), 1);
9017         let carol_revocation = match events[0] {
9018                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
9019                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
9020                         (*msg).clone()
9021                 },
9022                 _ => panic!("Unexpected event"),
9023         };
9024         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
9025         check_added_monitors!(nodes[1], 1);
9026
9027         // If this test requires the force-closed channel to not be on-chain until after the fulfill,
9028         // here's where we put said channel's commitment tx on-chain.
9029         let mut txn_to_broadcast = alice_txn.clone();
9030         if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
9031         if !go_onchain_before_fulfill {
9032                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
9033                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
9034                 // If Bob was the one to force-close, he will have already passed these checks earlier.
9035                 if broadcast_alice {
9036                         check_closed_broadcast!(nodes[1], true);
9037                         check_added_monitors!(nodes[1], 1);
9038                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
9039                 }
9040                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9041                 if broadcast_alice {
9042                         // In `connect_block()`, the ChainMonitor and ChannelManager are separately notified about a
9043                         // new block being connected. The ChannelManager being notified triggers a monitor update,
9044                         // which triggers broadcasting our commitment tx and an HTLC-claiming tx. The ChainMonitor
9045                         // being notified triggers the HTLC-claiming tx redundantly, resulting in 3 total txs being
9046                         // broadcasted.
9047                         assert_eq!(bob_txn.len(), 3);
9048                         check_spends!(bob_txn[1], chan_ab.3);
9049                 } else {
9050                         assert_eq!(bob_txn.len(), 2);
9051                         check_spends!(bob_txn[0], chan_ab.3);
9052                 }
9053         }
9054
9055         // Step (6):
9056         // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
9057         // broadcasted commitment transaction.
9058         {
9059                 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
9060                 if go_onchain_before_fulfill {
9061                         // Bob should now have an extra broadcasted tx, for the preimage-claiming transaction.
9062                         assert_eq!(bob_txn.len(), 2);
9063                 }
9064                 let script_weight = match broadcast_alice {
9065                         true => OFFERED_HTLC_SCRIPT_WEIGHT,
9066                         false => ACCEPTED_HTLC_SCRIPT_WEIGHT
9067                 };
9068                 // If Alice force-closed and Bob didn't receive her commitment transaction until after he
9069                 // received Carol's fulfill, he broadcasts the HTLC-output-claiming transaction first. Else if
9070                 // Bob force closed or if he found out about Alice's commitment tx before receiving Carol's
9071                 // fulfill, then he broadcasts the HTLC-output-claiming transaction second.
9072                 if broadcast_alice && !go_onchain_before_fulfill {
9073                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
9074                         assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
9075                 } else {
9076                         check_spends!(bob_txn[1], txn_to_broadcast[0]);
9077                         assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
9078                 }
9079         }
9080 }
9081
9082 #[test]
9083 fn test_onchain_htlc_settlement_after_close() {
9084         do_test_onchain_htlc_settlement_after_close(true, true);
9085         do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
9086         do_test_onchain_htlc_settlement_after_close(true, false);
9087         do_test_onchain_htlc_settlement_after_close(false, false);
9088 }
9089
9090 #[test]
9091 fn test_duplicate_chan_id() {
9092         // Test that if a given peer tries to open a channel with the same channel_id as one that is
9093         // already open we reject it and keep the old channel.
9094         //
9095         // Previously, full_stack_target managed to figure out that if you tried to open two channels
9096         // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
9097         // the existing channel when we detect the duplicate new channel, screwing up our monitor
9098         // updating logic for the existing channel.
9099         let chanmon_cfgs = create_chanmon_cfgs(2);
9100         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9101         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9102         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9103
9104         // Create an initial channel
9105         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9106         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9107         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_chan_msg);
9108         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()));
9109
9110         // Try to create a second channel with the same temporary_channel_id as the first and check
9111         // that it is rejected.
9112         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_chan_msg);
9113         {
9114                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9115                 assert_eq!(events.len(), 1);
9116                 match events[0] {
9117                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9118                                 // Technically, at this point, nodes[1] would be justified in thinking both the
9119                                 // first (valid) and second (invalid) channels are closed, given they both have
9120                                 // the same non-temporary channel_id. However, currently we do not, so we just
9121                                 // move forward with it.
9122                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9123                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9124                         },
9125                         _ => panic!("Unexpected event"),
9126                 }
9127         }
9128
9129         // Move the first channel through the funding flow...
9130         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
9131
9132         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9133         check_added_monitors!(nodes[0], 0);
9134
9135         let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9136         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
9137         {
9138                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
9139                 assert_eq!(added_monitors.len(), 1);
9140                 assert_eq!(added_monitors[0].0, funding_output);
9141                 added_monitors.clear();
9142         }
9143         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9144
9145         let funding_outpoint = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
9146         let channel_id = funding_outpoint.to_channel_id();
9147
9148         // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
9149         // temporary one).
9150
9151         // First try to open a second channel with a temporary channel id equal to the txid-based one.
9152         // Technically this is allowed by the spec, but we don't support it and there's little reason
9153         // to. Still, it shouldn't cause any other issues.
9154         open_chan_msg.temporary_channel_id = channel_id;
9155         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_chan_msg);
9156         {
9157                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9158                 assert_eq!(events.len(), 1);
9159                 match events[0] {
9160                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9161                                 // Technically, at this point, nodes[1] would be justified in thinking both
9162                                 // channels are closed, but currently we do not, so we just move forward with it.
9163                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9164                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9165                         },
9166                         _ => panic!("Unexpected event"),
9167                 }
9168         }
9169
9170         // Now try to create a second channel which has a duplicate funding output.
9171         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9172         let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9173         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_chan_2_msg);
9174         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()));
9175         create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
9176
9177         let funding_created = {
9178                 let mut a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
9179                 // Once we call `get_outbound_funding_created` the channel has a duplicate channel_id as
9180                 // another channel in the ChannelManager - an invalid state. Thus, we'd panic later when we
9181                 // try to create another channel. Instead, we drop the channel entirely here (leaving the
9182                 // channelmanager in a possibly nonsense state instead).
9183                 let mut as_chan = a_channel_lock.by_id.remove(&open_chan_2_msg.temporary_channel_id).unwrap();
9184                 let logger = test_utils::TestLogger::new();
9185                 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
9186         };
9187         check_added_monitors!(nodes[0], 0);
9188         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
9189         // At this point we'll try to add a duplicate channel monitor, which will be rejected, but
9190         // still needs to be cleared here.
9191         check_added_monitors!(nodes[1], 1);
9192
9193         // ...still, nodes[1] will reject the duplicate channel.
9194         {
9195                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9196                 assert_eq!(events.len(), 1);
9197                 match events[0] {
9198                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9199                                 // Technically, at this point, nodes[1] would be justified in thinking both
9200                                 // channels are closed, but currently we do not, so we just move forward with it.
9201                                 assert_eq!(msg.channel_id, channel_id);
9202                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9203                         },
9204                         _ => panic!("Unexpected event"),
9205                 }
9206         }
9207
9208         // finally, finish creating the original channel and send a payment over it to make sure
9209         // everything is functional.
9210         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
9211         {
9212                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9213                 assert_eq!(added_monitors.len(), 1);
9214                 assert_eq!(added_monitors[0].0, funding_output);
9215                 added_monitors.clear();
9216         }
9217
9218         let events_4 = nodes[0].node.get_and_clear_pending_events();
9219         assert_eq!(events_4.len(), 0);
9220         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9221         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9222
9223         let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9224         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9225         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9226
9227         send_payment(&nodes[0], &[&nodes[1]], 8000000);
9228 }
9229
9230 #[test]
9231 fn test_error_chans_closed() {
9232         // Test that we properly handle error messages, closing appropriate channels.
9233         //
9234         // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
9235         // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
9236         // we can test various edge cases around it to ensure we don't regress.
9237         let chanmon_cfgs = create_chanmon_cfgs(3);
9238         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9239         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9240         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9241
9242         // Create some initial channels
9243         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9244         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9245         let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9246
9247         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9248         assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
9249         assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
9250
9251         // Closing a channel from a different peer has no effect
9252         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
9253         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9254
9255         // Closing one channel doesn't impact others
9256         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
9257         check_added_monitors!(nodes[0], 1);
9258         check_closed_broadcast!(nodes[0], false);
9259         check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
9260         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
9261         assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
9262         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);
9263         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);
9264
9265         // A null channel ID should close all channels
9266         let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9267         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
9268         check_added_monitors!(nodes[0], 2);
9269         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
9270         let events = nodes[0].node.get_and_clear_pending_msg_events();
9271         assert_eq!(events.len(), 2);
9272         match events[0] {
9273                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9274                         assert_eq!(msg.contents.flags & 2, 2);
9275                 },
9276                 _ => panic!("Unexpected event"),
9277         }
9278         match events[1] {
9279                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9280                         assert_eq!(msg.contents.flags & 2, 2);
9281                 },
9282                 _ => panic!("Unexpected event"),
9283         }
9284         // Note that at this point users of a standard PeerHandler will end up calling
9285         // peer_disconnected with no_connection_possible set to false, duplicating the
9286         // close-all-channels logic. That's OK, we don't want to end up not force-closing channels for
9287         // users with their own peer handling logic. We duplicate the call here, however.
9288         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9289         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9290
9291         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
9292         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9293         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9294 }
9295
9296 #[test]
9297 fn test_invalid_funding_tx() {
9298         // Test that we properly handle invalid funding transactions sent to us from a peer.
9299         //
9300         // Previously, all other major lightning implementations had failed to properly sanitize
9301         // funding transactions from their counterparties, leading to a multi-implementation critical
9302         // security vulnerability (though we always sanitized properly, we've previously had
9303         // un-released crashes in the sanitization process).
9304         //
9305         // Further, if the funding transaction is consensus-valid, confirms, and is later spent, we'd
9306         // previously have crashed in `ChannelMonitor` even though we closed the channel as bogus and
9307         // gave up on it. We test this here by generating such a transaction.
9308         let chanmon_cfgs = create_chanmon_cfgs(2);
9309         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9310         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9311         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9312
9313         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
9314         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()));
9315         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()));
9316
9317         let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
9318
9319         // Create a witness program which can be spent by a 4-empty-stack-elements witness and which is
9320         // 136 bytes long. This matches our "accepted HTLC preimage spend" matching, previously causing
9321         // a panic as we'd try to extract a 32 byte preimage from a witness element without checking
9322         // its length.
9323         let mut wit_program: Vec<u8> = channelmonitor::deliberately_bogus_accepted_htlc_witness_program();
9324         let wit_program_script: Script = wit_program.into();
9325         for output in tx.output.iter_mut() {
9326                 // Make the confirmed funding transaction have a bogus script_pubkey
9327                 output.script_pubkey = Script::new_v0_p2wsh(&wit_program_script.wscript_hash());
9328         }
9329
9330         nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
9331         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()));
9332         check_added_monitors!(nodes[1], 1);
9333
9334         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()));
9335         check_added_monitors!(nodes[0], 1);
9336
9337         let events_1 = nodes[0].node.get_and_clear_pending_events();
9338         assert_eq!(events_1.len(), 0);
9339
9340         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9341         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9342         nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9343
9344         let expected_err = "funding tx had wrong script/value or output index";
9345         confirm_transaction_at(&nodes[1], &tx, 1);
9346         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
9347         check_added_monitors!(nodes[1], 1);
9348         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9349         assert_eq!(events_2.len(), 1);
9350         if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9351                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9352                 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
9353                         assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
9354                 } else { panic!(); }
9355         } else { panic!(); }
9356         assert_eq!(nodes[1].node.list_channels().len(), 0);
9357
9358         // Now confirm a spend of the (bogus) funding transaction. As long as the witness is 5 elements
9359         // long the ChannelMonitor will try to read 32 bytes from the second-to-last element, panicing
9360         // as its not 32 bytes long.
9361         let mut spend_tx = Transaction {
9362                 version: 2i32, lock_time: PackedLockTime::ZERO,
9363                 input: tx.output.iter().enumerate().map(|(idx, _)| TxIn {
9364                         previous_output: BitcoinOutPoint {
9365                                 txid: tx.txid(),
9366                                 vout: idx as u32,
9367                         },
9368                         script_sig: Script::new(),
9369                         sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
9370                         witness: Witness::from_vec(channelmonitor::deliberately_bogus_accepted_htlc_witness())
9371                 }).collect(),
9372                 output: vec![TxOut {
9373                         value: 1000,
9374                         script_pubkey: Script::new(),
9375                 }]
9376         };
9377         check_spends!(spend_tx, tx);
9378         mine_transaction(&nodes[1], &spend_tx);
9379 }
9380
9381 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9382         // In the first version of the chain::Confirm interface, after a refactor was made to not
9383         // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9384         // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9385         // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9386         // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9387         // spending transaction until height N+1 (or greater). This was due to the way
9388         // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9389         // spending transaction at the height the input transaction was confirmed at, not whether we
9390         // should broadcast a spending transaction at the current height.
9391         // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9392         // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9393         // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9394         // until we learned about an additional block.
9395         //
9396         // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9397         // aren't broadcasting transactions too early (ie not broadcasting them at all).
9398         let chanmon_cfgs = create_chanmon_cfgs(3);
9399         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9400         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9401         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9402         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9403
9404         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9405         let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9406         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9407         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
9408         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9409
9410         nodes[1].node.force_close_broadcasting_latest_txn(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
9411         check_closed_broadcast!(nodes[1], true);
9412         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
9413         check_added_monitors!(nodes[1], 1);
9414         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9415         assert_eq!(node_txn.len(), 1);
9416
9417         let conf_height = nodes[1].best_block_info().1;
9418         if !test_height_before_timelock {
9419                 connect_blocks(&nodes[1], 24 * 6);
9420         }
9421         nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9422                 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9423         if test_height_before_timelock {
9424                 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9425                 // generate any events or broadcast any transactions
9426                 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9427                 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9428         } else {
9429                 // We should broadcast an HTLC transaction spending our funding transaction first
9430                 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9431                 assert_eq!(spending_txn.len(), 2);
9432                 assert_eq!(spending_txn[0], node_txn[0]);
9433                 check_spends!(spending_txn[1], node_txn[0]);
9434                 // We should also generate a SpendableOutputs event with the to_self output (as its
9435                 // timelock is up).
9436                 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9437                 assert_eq!(descriptor_spend_txn.len(), 1);
9438
9439                 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9440                 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9441                 // additional block built on top of the current chain.
9442                 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9443                         &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9444                 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 }]);
9445                 check_added_monitors!(nodes[1], 1);
9446
9447                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9448                 assert!(updates.update_add_htlcs.is_empty());
9449                 assert!(updates.update_fulfill_htlcs.is_empty());
9450                 assert_eq!(updates.update_fail_htlcs.len(), 1);
9451                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9452                 assert!(updates.update_fee.is_none());
9453                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9454                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9455                 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9456         }
9457 }
9458
9459 #[test]
9460 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9461         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9462         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9463 }
9464
9465 #[test]
9466 fn test_forwardable_regen() {
9467         // Tests that if we reload a ChannelManager while forwards are pending we will regenerate the
9468         // PendingHTLCsForwardable event automatically, ensuring we don't forget to forward/receive
9469         // HTLCs.
9470         // We test it for both payment receipt and payment forwarding.
9471
9472         let chanmon_cfgs = create_chanmon_cfgs(3);
9473         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9474         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9475         let persister: test_utils::TestPersister;
9476         let new_chain_monitor: test_utils::TestChainMonitor;
9477         let nodes_1_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
9478         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9479         let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
9480         let chan_id_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
9481
9482         // First send a payment to nodes[1]
9483         let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
9484         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
9485         check_added_monitors!(nodes[0], 1);
9486
9487         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9488         assert_eq!(events.len(), 1);
9489         let payment_event = SendEvent::from_event(events.pop().unwrap());
9490         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9491         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9492
9493         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9494
9495         // Next send a payment which is forwarded by nodes[1]
9496         let (route_2, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 200_000);
9497         nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
9498         check_added_monitors!(nodes[0], 1);
9499
9500         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9501         assert_eq!(events.len(), 1);
9502         let payment_event = SendEvent::from_event(events.pop().unwrap());
9503         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9504         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9505
9506         // There is already a PendingHTLCsForwardable event "pending" so another one will not be
9507         // generated
9508         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
9509
9510         // Now restart nodes[1] and make sure it regenerates a single PendingHTLCsForwardable
9511         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9512         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9513
9514         let chan_0_monitor_serialized = get_monitor!(nodes[1], chan_id_1).encode();
9515         let chan_1_monitor_serialized = get_monitor!(nodes[1], chan_id_2).encode();
9516         reload_node!(nodes[1], nodes[1].node.encode(), &[&chan_0_monitor_serialized, &chan_1_monitor_serialized], persister, new_chain_monitor, nodes_1_deserialized);
9517
9518         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9519         // Note that nodes[1] and nodes[2] resend their channel_ready here since they haven't updated
9520         // the commitment state.
9521         reconnect_nodes(&nodes[1], &nodes[2], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9522
9523         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
9524
9525         expect_pending_htlcs_forwardable!(nodes[1]);
9526         expect_payment_received!(nodes[1], payment_hash, payment_secret, 100_000);
9527         check_added_monitors!(nodes[1], 1);
9528
9529         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9530         assert_eq!(events.len(), 1);
9531         let payment_event = SendEvent::from_event(events.pop().unwrap());
9532         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9533         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false);
9534         expect_pending_htlcs_forwardable!(nodes[2]);
9535         expect_payment_received!(nodes[2], payment_hash_2, payment_secret_2, 200_000);
9536
9537         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
9538         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage_2);
9539 }
9540
9541 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
9542         let chanmon_cfgs = create_chanmon_cfgs(2);
9543         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9544         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9545         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9546
9547         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9548
9549         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
9550                 .with_features(channelmanager::provided_invoice_features());
9551         let route = get_route!(nodes[0], payment_params, 10_000, TEST_FINAL_CLTV).unwrap();
9552
9553         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9554
9555         {
9556                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
9557                 check_added_monitors!(nodes[0], 1);
9558                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9559                 assert_eq!(events.len(), 1);
9560                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9561                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9562                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9563         }
9564         expect_pending_htlcs_forwardable!(nodes[1]);
9565         expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9566
9567         {
9568                 // Note that we use a different PaymentId here to allow us to duplicativly pay
9569                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_secret.0)).unwrap();
9570                 check_added_monitors!(nodes[0], 1);
9571                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9572                 assert_eq!(events.len(), 1);
9573                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9574                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9575                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9576                 // At this point, nodes[1] would notice it has too much value for the payment. It will
9577                 // assume the second is a privacy attack (no longer particularly relevant
9578                 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9579                 // the first HTLC delivered above.
9580         }
9581
9582         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9583         nodes[1].node.process_pending_htlc_forwards();
9584
9585         if test_for_second_fail_panic {
9586                 // Now we go fail back the first HTLC from the user end.
9587                 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9588
9589                 let expected_destinations = vec![
9590                         HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9591                         HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9592                 ];
9593                 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1],  expected_destinations);
9594                 nodes[1].node.process_pending_htlc_forwards();
9595
9596                 check_added_monitors!(nodes[1], 1);
9597                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9598                 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9599
9600                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9601                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9602                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9603
9604                 let failure_events = nodes[0].node.get_and_clear_pending_events();
9605                 assert_eq!(failure_events.len(), 2);
9606                 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9607                 if let Event::PaymentPathFailed { .. } = failure_events[1] {} else { panic!(); }
9608         } else {
9609                 // Let the second HTLC fail and claim the first
9610                 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9611                 nodes[1].node.process_pending_htlc_forwards();
9612
9613                 check_added_monitors!(nodes[1], 1);
9614                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9615                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9616                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9617
9618                 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9619
9620                 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9621         }
9622 }
9623
9624 #[test]
9625 fn test_dup_htlc_second_fail_panic() {
9626         // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9627         // value for the payment, we'd fail back both HTLCs after generating a `PaymentReceived` event.
9628         // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9629         // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9630         do_test_dup_htlc_second_rejected(true);
9631 }
9632
9633 #[test]
9634 fn test_dup_htlc_second_rejected() {
9635         // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9636         // simply reject the second HTLC but are still able to claim the first HTLC.
9637         do_test_dup_htlc_second_rejected(false);
9638 }
9639
9640 #[test]
9641 fn test_inconsistent_mpp_params() {
9642         // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9643         // such HTLC and allow the second to stay.
9644         let chanmon_cfgs = create_chanmon_cfgs(4);
9645         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9646         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9647         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9648
9649         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9650         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9651         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9652         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());
9653
9654         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id())
9655                 .with_features(channelmanager::provided_invoice_features());
9656         let mut route = get_route!(nodes[0], payment_params, 15_000_000, TEST_FINAL_CLTV).unwrap();
9657         assert_eq!(route.paths.len(), 2);
9658         route.paths.sort_by(|path_a, _| {
9659                 // Sort the path so that the path through nodes[1] comes first
9660                 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
9661                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9662         });
9663         let payment_params_opt = Some(payment_params);
9664
9665         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9666
9667         let cur_height = nodes[0].best_block_info().1;
9668         let payment_id = PaymentId([42; 32]);
9669
9670         let session_privs = {
9671                 // We create a fake route here so that we start with three pending HTLCs, which we'll
9672                 // ultimately have, just not right away.
9673                 let mut dup_route = route.clone();
9674                 dup_route.paths.push(route.paths[1].clone());
9675                 nodes[0].node.test_add_new_pending_payment(our_payment_hash, Some(our_payment_secret), payment_id, &dup_route).unwrap()
9676         };
9677         {
9678                 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();
9679                 check_added_monitors!(nodes[0], 1);
9680
9681                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9682                 assert_eq!(events.len(), 1);
9683                 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9684         }
9685         assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9686
9687         {
9688                 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();
9689                 check_added_monitors!(nodes[0], 1);
9690
9691                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9692                 assert_eq!(events.len(), 1);
9693                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9694
9695                 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9696                 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9697
9698                 expect_pending_htlcs_forwardable!(nodes[2]);
9699                 check_added_monitors!(nodes[2], 1);
9700
9701                 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9702                 assert_eq!(events.len(), 1);
9703                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9704
9705                 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9706                 check_added_monitors!(nodes[3], 0);
9707                 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9708
9709                 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9710                 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9711                 // post-payment_secrets) and fail back the new HTLC.
9712         }
9713         expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9714         nodes[3].node.process_pending_htlc_forwards();
9715         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9716         nodes[3].node.process_pending_htlc_forwards();
9717
9718         check_added_monitors!(nodes[3], 1);
9719
9720         let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9721         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9722         commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9723
9724         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 }]);
9725         check_added_monitors!(nodes[2], 1);
9726
9727         let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9728         nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9729         commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9730
9731         expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9732
9733         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();
9734         check_added_monitors!(nodes[0], 1);
9735
9736         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9737         assert_eq!(events.len(), 1);
9738         pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9739
9740         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9741 }
9742
9743 #[test]
9744 fn test_keysend_payments_to_public_node() {
9745         let chanmon_cfgs = create_chanmon_cfgs(2);
9746         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9747         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9748         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9749
9750         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9751         let network_graph = nodes[0].network_graph;
9752         let payer_pubkey = nodes[0].node.get_our_node_id();
9753         let payee_pubkey = nodes[1].node.get_our_node_id();
9754         let route_params = RouteParameters {
9755                 payment_params: PaymentParameters::for_keysend(payee_pubkey),
9756                 final_value_msat: 10000,
9757                 final_cltv_expiry_delta: 40,
9758         };
9759         let scorer = test_utils::TestScorer::with_penalty(0);
9760         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9761         let route = find_route(&payer_pubkey, &route_params, &network_graph, None, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
9762
9763         let test_preimage = PaymentPreimage([42; 32]);
9764         let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage), PaymentId(test_preimage.0)).unwrap();
9765         check_added_monitors!(nodes[0], 1);
9766         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9767         assert_eq!(events.len(), 1);
9768         let event = events.pop().unwrap();
9769         let path = vec![&nodes[1]];
9770         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9771         claim_payment(&nodes[0], &path, test_preimage);
9772 }
9773
9774 #[test]
9775 fn test_keysend_payments_to_private_node() {
9776         let chanmon_cfgs = create_chanmon_cfgs(2);
9777         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9778         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9779         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9780
9781         let payer_pubkey = nodes[0].node.get_our_node_id();
9782         let payee_pubkey = nodes[1].node.get_our_node_id();
9783         nodes[0].node.peer_connected(&payee_pubkey, &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
9784         nodes[1].node.peer_connected(&payer_pubkey, &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
9785
9786         let _chan = create_chan_between_nodes(&nodes[0], &nodes[1], channelmanager::provided_init_features(), channelmanager::provided_init_features());
9787         let route_params = RouteParameters {
9788                 payment_params: PaymentParameters::for_keysend(payee_pubkey),
9789                 final_value_msat: 10000,
9790                 final_cltv_expiry_delta: 40,
9791         };
9792         let network_graph = nodes[0].network_graph;
9793         let first_hops = nodes[0].node.list_usable_channels();
9794         let scorer = test_utils::TestScorer::with_penalty(0);
9795         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9796         let route = find_route(
9797                 &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
9798                 nodes[0].logger, &scorer, &random_seed_bytes
9799         ).unwrap();
9800
9801         let test_preimage = PaymentPreimage([42; 32]);
9802         let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage), PaymentId(test_preimage.0)).unwrap();
9803         check_added_monitors!(nodes[0], 1);
9804         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9805         assert_eq!(events.len(), 1);
9806         let event = events.pop().unwrap();
9807         let path = vec![&nodes[1]];
9808         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9809         claim_payment(&nodes[0], &path, test_preimage);
9810 }
9811
9812 #[test]
9813 fn test_double_partial_claim() {
9814         // Test what happens if a node receives a payment, generates a PaymentReceived event, the HTLCs
9815         // time out, the sender resends only some of the MPP parts, then the user processes the
9816         // PaymentReceived event, ensuring they don't inadvertently claim only part of the full payment
9817         // amount.
9818         let chanmon_cfgs = create_chanmon_cfgs(4);
9819         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9820         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9821         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9822
9823         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9824         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9825         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9826         create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9827
9828         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
9829         assert_eq!(route.paths.len(), 2);
9830         route.paths.sort_by(|path_a, _| {
9831                 // Sort the path so that the path through nodes[1] comes first
9832                 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
9833                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9834         });
9835
9836         send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 15_000_000, payment_hash, payment_secret);
9837         // nodes[3] has now received a PaymentReceived event...which it will take some (exorbitant)
9838         // amount of time to respond to.
9839
9840         // Connect some blocks to time out the payment
9841         connect_blocks(&nodes[3], TEST_FINAL_CLTV);
9842         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // To get the same height for sending later
9843
9844         let failed_destinations = vec![
9845                 HTLCDestination::FailedPayment { payment_hash },
9846                 HTLCDestination::FailedPayment { payment_hash },
9847         ];
9848         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations);
9849
9850         pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash);
9851
9852         // nodes[1] now retries one of the two paths...
9853         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
9854         check_added_monitors!(nodes[0], 2);
9855
9856         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9857         assert_eq!(events.len(), 2);
9858         pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
9859
9860         // At this point nodes[3] has received one half of the payment, and the user goes to handle
9861         // that PaymentReceived event they got hours ago and never handled...we should refuse to claim.
9862         nodes[3].node.claim_funds(payment_preimage);
9863         check_added_monitors!(nodes[3], 0);
9864         assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
9865 }
9866
9867 fn do_test_partial_claim_before_restart(persist_both_monitors: bool) {
9868         // Test what happens if a node receives an MPP payment, claims it, but crashes before
9869         // persisting the ChannelManager. If `persist_both_monitors` is false, also crash after only
9870         // updating one of the two channels' ChannelMonitors. As a result, on startup, we'll (a) still
9871         // have the PaymentReceived event, (b) have one (or two) channel(s) that goes on chain with the
9872         // HTLC preimage in them, and (c) optionally have one channel that is live off-chain but does
9873         // not have the preimage tied to the still-pending HTLC.
9874         //
9875         // To get to the correct state, on startup we should propagate the preimage to the
9876         // still-off-chain channel, claiming the HTLC as soon as the peer connects, with the monitor
9877         // receiving the preimage without a state update.
9878         //
9879         // Further, we should generate a `PaymentClaimed` event to inform the user that the payment was
9880         // definitely claimed.
9881         let chanmon_cfgs = create_chanmon_cfgs(4);
9882         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9883         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9884
9885         let persister: test_utils::TestPersister;
9886         let new_chain_monitor: test_utils::TestChainMonitor;
9887         let nodes_3_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
9888
9889         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9890
9891         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9892         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9893         let chan_id_persisted = create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
9894         let chan_id_not_persisted = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
9895
9896         // Create an MPP route for 15k sats, more than the default htlc-max of 10%
9897         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
9898         assert_eq!(route.paths.len(), 2);
9899         route.paths.sort_by(|path_a, _| {
9900                 // Sort the path so that the path through nodes[1] comes first
9901                 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
9902                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9903         });
9904
9905         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
9906         check_added_monitors!(nodes[0], 2);
9907
9908         // Send the payment through to nodes[3] *without* clearing the PaymentReceived event
9909         let mut send_events = nodes[0].node.get_and_clear_pending_msg_events();
9910         assert_eq!(send_events.len(), 2);
9911         do_pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), send_events[0].clone(), true, false, None);
9912         do_pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), send_events[1].clone(), true, false, None);
9913
9914         // Now that we have an MPP payment pending, get the latest encoded copies of nodes[3]'s
9915         // monitors and ChannelManager, for use later, if we don't want to persist both monitors.
9916         let mut original_monitor = test_utils::TestVecWriter(Vec::new());
9917         if !persist_both_monitors {
9918                 for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
9919                         if outpoint.to_channel_id() == chan_id_not_persisted {
9920                                 assert!(original_monitor.0.is_empty());
9921                                 nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut original_monitor).unwrap();
9922                         }
9923                 }
9924         }
9925
9926         let original_manager = nodes[3].node.encode();
9927
9928         expect_payment_received!(nodes[3], payment_hash, payment_secret, 15_000_000);
9929
9930         nodes[3].node.claim_funds(payment_preimage);
9931         check_added_monitors!(nodes[3], 2);
9932         expect_payment_claimed!(nodes[3], payment_hash, 15_000_000);
9933
9934         // Now fetch one of the two updated ChannelMonitors from nodes[3], and restart pretending we
9935         // crashed in between the two persistence calls - using one old ChannelMonitor and one new one,
9936         // with the old ChannelManager.
9937         let mut updated_monitor = test_utils::TestVecWriter(Vec::new());
9938         for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
9939                 if outpoint.to_channel_id() == chan_id_persisted {
9940                         assert!(updated_monitor.0.is_empty());
9941                         nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut updated_monitor).unwrap();
9942                 }
9943         }
9944         // If `persist_both_monitors` is set, get the second monitor here as well
9945         if persist_both_monitors {
9946                 for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
9947                         if outpoint.to_channel_id() == chan_id_not_persisted {
9948                                 assert!(original_monitor.0.is_empty());
9949                                 nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut original_monitor).unwrap();
9950                         }
9951                 }
9952         }
9953
9954         // Now restart nodes[3].
9955         reload_node!(nodes[3], original_manager, &[&updated_monitor.0, &original_monitor.0], persister, new_chain_monitor, nodes_3_deserialized);
9956
9957         // On startup the preimage should have been copied into the non-persisted monitor:
9958         assert!(get_monitor!(nodes[3], chan_id_persisted).get_stored_preimages().contains_key(&payment_hash));
9959         assert!(get_monitor!(nodes[3], chan_id_not_persisted).get_stored_preimages().contains_key(&payment_hash));
9960
9961         nodes[1].node.peer_disconnected(&nodes[3].node.get_our_node_id(), false);
9962         nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), false);
9963
9964         // During deserialization, we should have closed one channel and broadcast its latest
9965         // commitment transaction. We should also still have the original PaymentReceived event we
9966         // never finished processing.
9967         let events = nodes[3].node.get_and_clear_pending_events();
9968         assert_eq!(events.len(), if persist_both_monitors { 4 } else { 3 });
9969         if let Event::PaymentReceived { amount_msat: 15_000_000, .. } = events[0] { } else { panic!(); }
9970         if let Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } = events[1] { } else { panic!(); }
9971         if persist_both_monitors {
9972                 if let Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } = events[2] { } else { panic!(); }
9973         }
9974
9975         // On restart, we should also get a duplicate PaymentClaimed event as we persisted the
9976         // ChannelManager prior to handling the original one.
9977         if let Event::PaymentClaimed { payment_hash: our_payment_hash, amount_msat: 15_000_000, .. } =
9978                 events[if persist_both_monitors { 3 } else { 2 }]
9979         {
9980                 assert_eq!(payment_hash, our_payment_hash);
9981         } else { panic!(); }
9982
9983         assert_eq!(nodes[3].node.list_channels().len(), if persist_both_monitors { 0 } else { 1 });
9984         if !persist_both_monitors {
9985                 // If one of the two channels is still live, reveal the payment preimage over it.
9986
9987                 nodes[3].node.peer_connected(&nodes[2].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
9988                 let reestablish_1 = get_chan_reestablish_msgs!(nodes[3], nodes[2]);
9989                 nodes[2].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
9990                 let reestablish_2 = get_chan_reestablish_msgs!(nodes[2], nodes[3]);
9991
9992                 nodes[2].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish_1[0]);
9993                 get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, nodes[3].node.get_our_node_id());
9994                 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
9995
9996                 nodes[3].node.handle_channel_reestablish(&nodes[2].node.get_our_node_id(), &reestablish_2[0]);
9997
9998                 // Once we call `get_and_clear_pending_msg_events` the holding cell is cleared and the HTLC
9999                 // claim should fly.
10000                 let ds_msgs = nodes[3].node.get_and_clear_pending_msg_events();
10001                 check_added_monitors!(nodes[3], 1);
10002                 assert_eq!(ds_msgs.len(), 2);
10003                 if let MessageSendEvent::SendChannelUpdate { .. } = ds_msgs[1] {} else { panic!(); }
10004
10005                 let cs_updates = match ds_msgs[0] {
10006                         MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
10007                                 nodes[2].node.handle_update_fulfill_htlc(&nodes[3].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
10008                                 check_added_monitors!(nodes[2], 1);
10009                                 let cs_updates = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
10010                                 expect_payment_forwarded!(nodes[2], nodes[0], nodes[3], Some(1000), false, false);
10011                                 commitment_signed_dance!(nodes[2], nodes[3], updates.commitment_signed, false, true);
10012                                 cs_updates
10013                         }
10014                         _ => panic!(),
10015                 };
10016
10017                 nodes[0].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &cs_updates.update_fulfill_htlcs[0]);
10018                 commitment_signed_dance!(nodes[0], nodes[2], cs_updates.commitment_signed, false, true);
10019                 expect_payment_sent!(nodes[0], payment_preimage);
10020         }
10021 }
10022
10023 #[test]
10024 fn test_partial_claim_before_restart() {
10025         do_test_partial_claim_before_restart(false);
10026         do_test_partial_claim_before_restart(true);
10027 }
10028
10029 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
10030 #[derive(Clone, Copy, PartialEq)]
10031 enum ExposureEvent {
10032         /// Breach occurs at HTLC forwarding (see `send_htlc`)
10033         AtHTLCForward,
10034         /// Breach occurs at HTLC reception (see `update_add_htlc`)
10035         AtHTLCReception,
10036         /// Breach occurs at outbound update_fee (see `send_update_fee`)
10037         AtUpdateFeeOutbound,
10038 }
10039
10040 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool) {
10041         // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
10042         // policy.
10043         //
10044         // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
10045         // trimmed-to-dust HTLC outbound balance and this new payment as included on next
10046         // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
10047         // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
10048         // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
10049         // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
10050         // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
10051         // might be available again for HTLC processing once the dust bandwidth has cleared up.
10052
10053         let chanmon_cfgs = create_chanmon_cfgs(2);
10054         let mut config = test_default_channel_config();
10055         config.channel_config.max_dust_htlc_exposure_msat = 5_000_000; // default setting value
10056         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10057         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
10058         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10059
10060         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
10061         let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10062         open_channel.max_htlc_value_in_flight_msat = 50_000_000;
10063         open_channel.max_accepted_htlcs = 60;
10064         if on_holder_tx {
10065                 open_channel.dust_limit_satoshis = 546;
10066         }
10067         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_channel);
10068         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10069         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_channel);
10070
10071         let opt_anchors = false;
10072
10073         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
10074
10075         if on_holder_tx {
10076                 if let Some(mut chan) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&temporary_channel_id) {
10077                         chan.holder_dust_limit_satoshis = 546;
10078                 }
10079         }
10080
10081         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
10082         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()));
10083         check_added_monitors!(nodes[1], 1);
10084
10085         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()));
10086         check_added_monitors!(nodes[0], 1);
10087
10088         let (channel_ready, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
10089         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
10090         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
10091
10092         let dust_buffer_feerate = {
10093                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
10094                 let chan = chan_lock.by_id.get(&channel_id).unwrap();
10095                 chan.get_dust_buffer_feerate(None) as u64
10096         };
10097         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;
10098         let dust_outbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
10099
10100         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;
10101         let dust_inbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
10102
10103         let dust_htlc_on_counterparty_tx: u64 = 25;
10104         let dust_htlc_on_counterparty_tx_msat: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
10105
10106         if on_holder_tx {
10107                 if dust_outbound_balance {
10108                         // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
10109                         // Outbound dust balance: 4372 sats
10110                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
10111                         for i in 0..dust_outbound_htlc_on_holder_tx {
10112                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
10113                                 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); }
10114                         }
10115                 } else {
10116                         // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
10117                         // Inbound dust balance: 4372 sats
10118                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
10119                         for _ in 0..dust_inbound_htlc_on_holder_tx {
10120                                 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
10121                         }
10122                 }
10123         } else {
10124                 if dust_outbound_balance {
10125                         // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
10126                         // Outbound dust balance: 5000 sats
10127                         for i in 0..dust_htlc_on_counterparty_tx {
10128                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
10129                                 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); }
10130                         }
10131                 } else {
10132                         // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
10133                         // Inbound dust balance: 5000 sats
10134                         for _ in 0..dust_htlc_on_counterparty_tx {
10135                                 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
10136                         }
10137                 }
10138         }
10139
10140         let dust_overflow = dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx + 1);
10141         if exposure_breach_event == ExposureEvent::AtHTLCForward {
10142                 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 });
10143                 let mut config = UserConfig::default();
10144                 // With default dust exposure: 5000 sats
10145                 if on_holder_tx {
10146                         let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * (dust_outbound_htlc_on_holder_tx + 1);
10147                         let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * dust_inbound_htlc_on_holder_tx + dust_outbound_htlc_on_holder_tx_msat;
10148                         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)));
10149                 } else {
10150                         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)));
10151                 }
10152         } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
10153                 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 });
10154                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
10155                 check_added_monitors!(nodes[1], 1);
10156                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
10157                 assert_eq!(events.len(), 1);
10158                 let payment_event = SendEvent::from_event(events.remove(0));
10159                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
10160                 // With default dust exposure: 5000 sats
10161                 if on_holder_tx {
10162                         // Outbound dust balance: 6399 sats
10163                         let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
10164                         let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
10165                         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);
10166                 } else {
10167                         // Outbound dust balance: 5200 sats
10168                         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);
10169                 }
10170         } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
10171                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 2_500_000);
10172                 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", ); }
10173                 {
10174                         let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
10175                         *feerate_lock = *feerate_lock * 10;
10176                 }
10177                 nodes[0].node.timer_tick_occurred();
10178                 check_added_monitors!(nodes[0], 1);
10179                 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);
10180         }
10181
10182         let _ = nodes[0].node.get_and_clear_pending_msg_events();
10183         let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
10184         added_monitors.clear();
10185 }
10186
10187 #[test]
10188 fn test_max_dust_htlc_exposure() {
10189         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true);
10190         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true);
10191         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true);
10192         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false);
10193         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false);
10194         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false);
10195         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true);
10196         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false);
10197         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true);
10198         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false);
10199         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false);
10200         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true);
10201 }
10202
10203 #[test]
10204 fn test_non_final_funding_tx() {
10205         let chanmon_cfgs = create_chanmon_cfgs(2);
10206         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10207         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10208         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10209
10210         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
10211         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10212         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_channel_message);
10213         let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10214         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_channel_message);
10215
10216         let best_height = nodes[0].node.best_block.read().unwrap().height();
10217
10218         let chan_id = *nodes[0].network_chan_count.borrow();
10219         let events = nodes[0].node.get_and_clear_pending_events();
10220         let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::Script::new(), sequence: Sequence(1), witness: Witness::from_vec(vec!(vec!(1))) };
10221         assert_eq!(events.len(), 1);
10222         let mut tx = match events[0] {
10223                 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
10224                         // Timelock the transaction _beyond_ the best client height + 2.
10225                         Transaction { version: chan_id as i32, lock_time: PackedLockTime(best_height + 3), input: vec![input], output: vec![TxOut {
10226                                 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
10227                         }]}
10228                 },
10229                 _ => panic!("Unexpected event"),
10230         };
10231         // Transaction should fail as it's evaluated as non-final for propagation.
10232         match nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()) {
10233                 Err(APIError::APIMisuseError { err }) => {
10234                         assert_eq!(format!("Funding transaction absolute timelock is non-final"), err);
10235                 },
10236                 _ => panic!()
10237         }
10238
10239         // However, transaction should be accepted if it's in a +2 headroom from best block.
10240         tx.lock_time = PackedLockTime(tx.lock_time.0 - 1);
10241         assert!(nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
10242         get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
10243 }