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