0709b64fcba88509ac3d288749809840d252cb19
[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 }
562
563 #[test]
564 fn test_sanity_on_in_flight_opens() {
565         do_test_sanity_on_in_flight_opens(0);
566         do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
567         do_test_sanity_on_in_flight_opens(1);
568         do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
569         do_test_sanity_on_in_flight_opens(2);
570         do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
571         do_test_sanity_on_in_flight_opens(3);
572         do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
573         do_test_sanity_on_in_flight_opens(4);
574         do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
575         do_test_sanity_on_in_flight_opens(5);
576         do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
577         do_test_sanity_on_in_flight_opens(6);
578         do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
579         do_test_sanity_on_in_flight_opens(7);
580         do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
581         do_test_sanity_on_in_flight_opens(8);
582         do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
583 }
584
585 #[test]
586 fn test_update_fee_vanilla() {
587         let chanmon_cfgs = create_chanmon_cfgs(2);
588         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
589         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
590         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
591         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
592
593         {
594                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
595                 *feerate_lock += 25;
596         }
597         nodes[0].node.timer_tick_occurred();
598         check_added_monitors!(nodes[0], 1);
599
600         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
601         assert_eq!(events_0.len(), 1);
602         let (update_msg, commitment_signed) = match events_0[0] {
603                         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 } } => {
604                         (update_fee.as_ref(), commitment_signed)
605                 },
606                 _ => panic!("Unexpected event"),
607         };
608         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
609
610         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
611         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
612         check_added_monitors!(nodes[1], 1);
613
614         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
615         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
616         check_added_monitors!(nodes[0], 1);
617
618         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
619         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
620         // No commitment_signed so get_event_msg's assert(len == 1) passes
621         check_added_monitors!(nodes[0], 1);
622
623         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
624         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
625         check_added_monitors!(nodes[1], 1);
626 }
627
628 #[test]
629 fn test_update_fee_that_funder_cannot_afford() {
630         let chanmon_cfgs = create_chanmon_cfgs(2);
631         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
632         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
633         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
634         let channel_value = 5000;
635         let push_sats = 700;
636         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());
637         let channel_id = chan.2;
638         let secp_ctx = Secp256k1::new();
639         let default_config = UserConfig::default();
640         let bs_channel_reserve_sats = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value, &default_config);
641
642         let opt_anchors = false;
643
644         // Calculate the maximum feerate that A can afford. Note that we don't send an update_fee
645         // CONCURRENT_INBOUND_HTLC_FEE_BUFFER HTLCs before actually running out of local balance, so we
646         // calculate two different feerates here - the expected local limit as well as the expected
647         // remote limit.
648         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;
649         let non_buffer_feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / commitment_tx_base_weight(opt_anchors)) as u32;
650         {
651                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
652                 *feerate_lock = feerate;
653         }
654         nodes[0].node.timer_tick_occurred();
655         check_added_monitors!(nodes[0], 1);
656         let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
657
658         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
659
660         commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
661
662         // Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate set above.
663         {
664                 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
665
666                 //We made sure neither party's funds are below the dust limit and there are no HTLCs here
667                 assert_eq!(commitment_tx.output.len(), 2);
668                 let total_fee: u64 = commit_tx_fee_msat(feerate, 0, opt_anchors) / 1000;
669                 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
670                 actual_fee = channel_value - actual_fee;
671                 assert_eq!(total_fee, actual_fee);
672         }
673
674         {
675                 // Increment the feerate by a small constant, accounting for rounding errors
676                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
677                 *feerate_lock += 4;
678         }
679         nodes[0].node.timer_tick_occurred();
680         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot afford to send new feerate at {}", feerate + 4), 1);
681         check_added_monitors!(nodes[0], 0);
682
683         const INITIAL_COMMITMENT_NUMBER: u64 = 281474976710654;
684
685         // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
686         // needed to sign the new commitment tx and (2) sign the new commitment tx.
687         let (local_revocation_basepoint, local_htlc_basepoint, local_funding) = {
688                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
689                 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
690                 let chan_signer = local_chan.get_signer();
691                 let pubkeys = chan_signer.pubkeys();
692                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
693                  pubkeys.funding_pubkey)
694         };
695         let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point, remote_funding) = {
696                 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
697                 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
698                 let chan_signer = remote_chan.get_signer();
699                 let pubkeys = chan_signer.pubkeys();
700                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
701                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
702                  pubkeys.funding_pubkey)
703         };
704
705         // Assemble the set of keys we can use for signatures for our commitment_signed message.
706         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
707                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
708
709         let res = {
710                 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
711                 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
712                 let local_chan_signer = local_chan.get_signer();
713                 let mut htlcs: Vec<(HTLCOutputInCommitment, ())> = vec![];
714                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
715                         INITIAL_COMMITMENT_NUMBER - 1,
716                         push_sats,
717                         channel_value - push_sats - commit_tx_fee_msat(non_buffer_feerate + 4, 0, opt_anchors) / 1000,
718                         opt_anchors, local_funding, remote_funding,
719                         commit_tx_keys.clone(),
720                         non_buffer_feerate + 4,
721                         &mut htlcs,
722                         &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
723                 );
724                 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
725         };
726
727         let commit_signed_msg = msgs::CommitmentSigned {
728                 channel_id: chan.2,
729                 signature: res.0,
730                 htlc_signatures: res.1
731         };
732
733         let update_fee = msgs::UpdateFee {
734                 channel_id: chan.2,
735                 feerate_per_kw: non_buffer_feerate + 4,
736         };
737
738         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_fee);
739
740         //While producing the commitment_signed response after handling a received update_fee request the
741         //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
742         //Should produce and error.
743         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
744         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
745         check_added_monitors!(nodes[1], 1);
746         check_closed_broadcast!(nodes[1], true);
747         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: String::from("Funding remote cannot afford proposed new fee") });
748 }
749
750 #[test]
751 fn test_update_fee_with_fundee_update_add_htlc() {
752         let chanmon_cfgs = create_chanmon_cfgs(2);
753         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
754         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
755         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
756         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
757
758         // balancing
759         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
760
761         {
762                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
763                 *feerate_lock += 20;
764         }
765         nodes[0].node.timer_tick_occurred();
766         check_added_monitors!(nodes[0], 1);
767
768         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
769         assert_eq!(events_0.len(), 1);
770         let (update_msg, commitment_signed) = match events_0[0] {
771                         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 } } => {
772                         (update_fee.as_ref(), commitment_signed)
773                 },
774                 _ => panic!("Unexpected event"),
775         };
776         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
777         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
778         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
779         check_added_monitors!(nodes[1], 1);
780
781         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 800000);
782
783         // nothing happens since node[1] is in AwaitingRemoteRevoke
784         nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
785         {
786                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
787                 assert_eq!(added_monitors.len(), 0);
788                 added_monitors.clear();
789         }
790         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
791         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
792         // node[1] has nothing to do
793
794         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
795         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
796         check_added_monitors!(nodes[0], 1);
797
798         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
799         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
800         // No commitment_signed so get_event_msg's assert(len == 1) passes
801         check_added_monitors!(nodes[0], 1);
802         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
803         check_added_monitors!(nodes[1], 1);
804         // AwaitingRemoteRevoke ends here
805
806         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
807         assert_eq!(commitment_update.update_add_htlcs.len(), 1);
808         assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
809         assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
810         assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
811         assert_eq!(commitment_update.update_fee.is_none(), true);
812
813         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
814         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
815         check_added_monitors!(nodes[0], 1);
816         let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
817
818         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
819         check_added_monitors!(nodes[1], 1);
820         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
821
822         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
823         check_added_monitors!(nodes[1], 1);
824         let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
825         // No commitment_signed so get_event_msg's assert(len == 1) passes
826
827         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
828         check_added_monitors!(nodes[0], 1);
829         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
830
831         expect_pending_htlcs_forwardable!(nodes[0]);
832
833         let events = nodes[0].node.get_and_clear_pending_events();
834         assert_eq!(events.len(), 1);
835         match events[0] {
836                 Event::PaymentReceived { .. } => { },
837                 _ => panic!("Unexpected event"),
838         };
839
840         claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
841
842         send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
843         send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
844         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
845         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
846         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
847 }
848
849 #[test]
850 fn test_update_fee() {
851         let chanmon_cfgs = create_chanmon_cfgs(2);
852         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
853         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
854         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
855         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
856         let channel_id = chan.2;
857
858         // A                                        B
859         // (1) update_fee/commitment_signed      ->
860         //                                       <- (2) revoke_and_ack
861         //                                       .- send (3) commitment_signed
862         // (4) update_fee/commitment_signed      ->
863         //                                       .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
864         //                                       <- (3) commitment_signed delivered
865         // send (6) revoke_and_ack               -.
866         //                                       <- (5) deliver revoke_and_ack
867         // (6) deliver revoke_and_ack            ->
868         //                                       .- send (7) commitment_signed in response to (4)
869         //                                       <- (7) deliver commitment_signed
870         // revoke_and_ack                        ->
871
872         // Create and deliver (1)...
873         let feerate;
874         {
875                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
876                 feerate = *feerate_lock;
877                 *feerate_lock = feerate + 20;
878         }
879         nodes[0].node.timer_tick_occurred();
880         check_added_monitors!(nodes[0], 1);
881
882         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
883         assert_eq!(events_0.len(), 1);
884         let (update_msg, commitment_signed) = match events_0[0] {
885                         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 } } => {
886                         (update_fee.as_ref(), commitment_signed)
887                 },
888                 _ => panic!("Unexpected event"),
889         };
890         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
891
892         // Generate (2) and (3):
893         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
894         let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
895         check_added_monitors!(nodes[1], 1);
896
897         // Deliver (2):
898         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
899         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
900         check_added_monitors!(nodes[0], 1);
901
902         // Create and deliver (4)...
903         {
904                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
905                 *feerate_lock = feerate + 30;
906         }
907         nodes[0].node.timer_tick_occurred();
908         check_added_monitors!(nodes[0], 1);
909         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
910         assert_eq!(events_0.len(), 1);
911         let (update_msg, commitment_signed) = match events_0[0] {
912                         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 } } => {
913                         (update_fee.as_ref(), commitment_signed)
914                 },
915                 _ => panic!("Unexpected event"),
916         };
917
918         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
919         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
920         check_added_monitors!(nodes[1], 1);
921         // ... creating (5)
922         let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
923         // No commitment_signed so get_event_msg's assert(len == 1) passes
924
925         // Handle (3), creating (6):
926         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
927         check_added_monitors!(nodes[0], 1);
928         let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
929         // No commitment_signed so get_event_msg's assert(len == 1) passes
930
931         // Deliver (5):
932         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
933         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
934         check_added_monitors!(nodes[0], 1);
935
936         // Deliver (6), creating (7):
937         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
938         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
939         assert!(commitment_update.update_add_htlcs.is_empty());
940         assert!(commitment_update.update_fulfill_htlcs.is_empty());
941         assert!(commitment_update.update_fail_htlcs.is_empty());
942         assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
943         assert!(commitment_update.update_fee.is_none());
944         check_added_monitors!(nodes[1], 1);
945
946         // Deliver (7)
947         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
948         check_added_monitors!(nodes[0], 1);
949         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
950         // No commitment_signed so get_event_msg's assert(len == 1) passes
951
952         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
953         check_added_monitors!(nodes[1], 1);
954         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
955
956         assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
957         assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
958         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
959         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
960         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
961 }
962
963 #[test]
964 fn fake_network_test() {
965         // Simple test which builds a network of ChannelManagers, connects them to each other, and
966         // tests that payments get routed and transactions broadcast in semi-reasonable ways.
967         let chanmon_cfgs = create_chanmon_cfgs(4);
968         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
969         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
970         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
971
972         // Create some initial channels
973         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
974         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
975         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
976
977         // Rebalance the network a bit by relaying one payment through all the channels...
978         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
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
983         // Send some more payments
984         send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
985         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
986         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
987
988         // Test failure packets
989         let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
990         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
991
992         // Add a new channel that skips 3
993         let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
994
995         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
996         send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
997         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
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
1003         // Do some rebalance loop payments, simultaneously
1004         let mut hops = Vec::with_capacity(3);
1005         hops.push(RouteHop {
1006                 pubkey: nodes[2].node.get_our_node_id(),
1007                 node_features: NodeFeatures::empty(),
1008                 short_channel_id: chan_2.0.contents.short_channel_id,
1009                 channel_features: ChannelFeatures::empty(),
1010                 fee_msat: 0,
1011                 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1012         });
1013         hops.push(RouteHop {
1014                 pubkey: nodes[3].node.get_our_node_id(),
1015                 node_features: NodeFeatures::empty(),
1016                 short_channel_id: chan_3.0.contents.short_channel_id,
1017                 channel_features: ChannelFeatures::empty(),
1018                 fee_msat: 0,
1019                 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1020         });
1021         hops.push(RouteHop {
1022                 pubkey: nodes[1].node.get_our_node_id(),
1023                 node_features: channelmanager::provided_node_features(),
1024                 short_channel_id: chan_4.0.contents.short_channel_id,
1025                 channel_features: channelmanager::provided_channel_features(),
1026                 fee_msat: 1000000,
1027                 cltv_expiry_delta: TEST_FINAL_CLTV,
1028         });
1029         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;
1030         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;
1031         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;
1032
1033         let mut hops = Vec::with_capacity(3);
1034         hops.push(RouteHop {
1035                 pubkey: nodes[3].node.get_our_node_id(),
1036                 node_features: NodeFeatures::empty(),
1037                 short_channel_id: chan_4.0.contents.short_channel_id,
1038                 channel_features: ChannelFeatures::empty(),
1039                 fee_msat: 0,
1040                 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1041         });
1042         hops.push(RouteHop {
1043                 pubkey: nodes[2].node.get_our_node_id(),
1044                 node_features: NodeFeatures::empty(),
1045                 short_channel_id: chan_3.0.contents.short_channel_id,
1046                 channel_features: ChannelFeatures::empty(),
1047                 fee_msat: 0,
1048                 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1049         });
1050         hops.push(RouteHop {
1051                 pubkey: nodes[1].node.get_our_node_id(),
1052                 node_features: channelmanager::provided_node_features(),
1053                 short_channel_id: chan_2.0.contents.short_channel_id,
1054                 channel_features: channelmanager::provided_channel_features(),
1055                 fee_msat: 1000000,
1056                 cltv_expiry_delta: TEST_FINAL_CLTV,
1057         });
1058         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;
1059         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;
1060         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;
1061
1062         // Claim the rebalances...
1063         fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1064         claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1065
1066         // Close down the channels...
1067         close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1068         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
1069         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1070         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1071         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1072         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1073         close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1074         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1075         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1076         close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1077         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1078         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1079 }
1080
1081 #[test]
1082 fn holding_cell_htlc_counting() {
1083         // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1084         // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1085         // commitment dance rounds.
1086         let chanmon_cfgs = create_chanmon_cfgs(3);
1087         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1088         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1089         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1090         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1091         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1092
1093         let mut payments = Vec::new();
1094         for _ in 0..crate::ln::channel::OUR_MAX_HTLCS {
1095                 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1096                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
1097                 payments.push((payment_preimage, payment_hash));
1098         }
1099         check_added_monitors!(nodes[1], 1);
1100
1101         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1102         assert_eq!(events.len(), 1);
1103         let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1104         assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1105
1106         // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1107         // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1108         // another HTLC.
1109         let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1110         {
1111                 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 },
1112                         assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1113                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1114                 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1115         }
1116
1117         // This should also be true if we try to forward a payment.
1118         let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1119         {
1120                 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
1121                 check_added_monitors!(nodes[0], 1);
1122         }
1123
1124         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1125         assert_eq!(events.len(), 1);
1126         let payment_event = SendEvent::from_event(events.pop().unwrap());
1127         assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1128
1129         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1130         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1131         // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1132         // fails), the second will process the resulting failure and fail the HTLC backward.
1133         expect_pending_htlcs_forwardable!(nodes[1]);
1134         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 }]);
1135         check_added_monitors!(nodes[1], 1);
1136
1137         let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1138         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1139         commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1140
1141         expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1142
1143         // Now forward all the pending HTLCs and claim them back
1144         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1145         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1146         check_added_monitors!(nodes[2], 1);
1147
1148         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1149         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1150         check_added_monitors!(nodes[1], 1);
1151         let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1152
1153         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1154         check_added_monitors!(nodes[1], 1);
1155         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1156
1157         for ref update in as_updates.update_add_htlcs.iter() {
1158                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1159         }
1160         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1161         check_added_monitors!(nodes[2], 1);
1162         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1163         check_added_monitors!(nodes[2], 1);
1164         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1165
1166         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1167         check_added_monitors!(nodes[1], 1);
1168         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1169         check_added_monitors!(nodes[1], 1);
1170         let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1171
1172         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1173         check_added_monitors!(nodes[2], 1);
1174
1175         expect_pending_htlcs_forwardable!(nodes[2]);
1176
1177         let events = nodes[2].node.get_and_clear_pending_events();
1178         assert_eq!(events.len(), payments.len());
1179         for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1180                 match event {
1181                         &Event::PaymentReceived { ref payment_hash, .. } => {
1182                                 assert_eq!(*payment_hash, *hash);
1183                         },
1184                         _ => panic!("Unexpected event"),
1185                 };
1186         }
1187
1188         for (preimage, _) in payments.drain(..) {
1189                 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1190         }
1191
1192         send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1193 }
1194
1195 #[test]
1196 fn duplicate_htlc_test() {
1197         // Test that we accept duplicate payment_hash HTLCs across the network and that
1198         // claiming/failing them are all separate and don't affect each other
1199         let chanmon_cfgs = create_chanmon_cfgs(6);
1200         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1201         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1202         let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1203
1204         // Create some initial channels to route via 3 to 4/5 from 0/1/2
1205         create_announced_chan_between_nodes(&nodes, 0, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1206         create_announced_chan_between_nodes(&nodes, 1, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1207         create_announced_chan_between_nodes(&nodes, 2, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1208         create_announced_chan_between_nodes(&nodes, 3, 4, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1209         create_announced_chan_between_nodes(&nodes, 3, 5, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1210
1211         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1212
1213         *nodes[0].network_payment_count.borrow_mut() -= 1;
1214         assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1215
1216         *nodes[0].network_payment_count.borrow_mut() -= 1;
1217         assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1218
1219         claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1220         fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1221         claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1222 }
1223
1224 #[test]
1225 fn test_duplicate_htlc_different_direction_onchain() {
1226         // Test that ChannelMonitor doesn't generate 2 preimage txn
1227         // when we have 2 HTLCs with same preimage that go across a node
1228         // in opposite directions, even with the same payment secret.
1229         let chanmon_cfgs = create_chanmon_cfgs(2);
1230         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1231         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1232         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1233
1234         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1235
1236         // balancing
1237         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1238
1239         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1240
1241         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1242         let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200).unwrap();
1243         send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1244
1245         // Provide preimage to node 0 by claiming payment
1246         nodes[0].node.claim_funds(payment_preimage);
1247         expect_payment_claimed!(nodes[0], payment_hash, 800_000);
1248         check_added_monitors!(nodes[0], 1);
1249
1250         // Broadcast node 1 commitment txn
1251         let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1252
1253         assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1254         let mut has_both_htlcs = 0; // check htlcs match ones committed
1255         for outp in remote_txn[0].output.iter() {
1256                 if outp.value == 800_000 / 1000 {
1257                         has_both_htlcs += 1;
1258                 } else if outp.value == 900_000 / 1000 {
1259                         has_both_htlcs += 1;
1260                 }
1261         }
1262         assert_eq!(has_both_htlcs, 2);
1263
1264         mine_transaction(&nodes[0], &remote_txn[0]);
1265         check_added_monitors!(nodes[0], 1);
1266         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
1267         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
1268
1269         let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1270         assert_eq!(claim_txn.len(), 5);
1271
1272         check_spends!(claim_txn[0], remote_txn[0]); // Immediate HTLC claim with preimage
1273         check_spends!(claim_txn[1], chan_1.3); // Alternative commitment tx
1274         check_spends!(claim_txn[2], claim_txn[1]); // HTLC spend in alternative commitment tx
1275
1276         check_spends!(claim_txn[3], remote_txn[0]);
1277         check_spends!(claim_txn[4], remote_txn[0]);
1278         let preimage_tx = &claim_txn[0];
1279         let (preimage_bump_tx, timeout_tx) = if claim_txn[3].input[0].previous_output == preimage_tx.input[0].previous_output {
1280                 (&claim_txn[3], &claim_txn[4])
1281         } else {
1282                 (&claim_txn[4], &claim_txn[3])
1283         };
1284
1285         assert_eq!(preimage_tx.input.len(), 1);
1286         assert_eq!(preimage_bump_tx.input.len(), 1);
1287
1288         assert_eq!(preimage_tx.input.len(), 1);
1289         assert_eq!(preimage_tx.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1290         assert_eq!(remote_txn[0].output[preimage_tx.input[0].previous_output.vout as usize].value, 800);
1291
1292         assert_eq!(timeout_tx.input.len(), 1);
1293         assert_eq!(timeout_tx.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1294         check_spends!(timeout_tx, remote_txn[0]);
1295         assert_eq!(remote_txn[0].output[timeout_tx.input[0].previous_output.vout as usize].value, 900);
1296
1297         let events = nodes[0].node.get_and_clear_pending_msg_events();
1298         assert_eq!(events.len(), 3);
1299         for e in events {
1300                 match e {
1301                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1302                         MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1303                                 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1304                                 assert_eq!(msg.data, "Channel closed because commitment or closing transaction was confirmed on chain.");
1305                         },
1306                         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, .. } } => {
1307                                 assert!(update_add_htlcs.is_empty());
1308                                 assert!(update_fail_htlcs.is_empty());
1309                                 assert_eq!(update_fulfill_htlcs.len(), 1);
1310                                 assert!(update_fail_malformed_htlcs.is_empty());
1311                                 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1312                         },
1313                         _ => panic!("Unexpected event"),
1314                 }
1315         }
1316 }
1317
1318 #[test]
1319 fn test_basic_channel_reserve() {
1320         let chanmon_cfgs = create_chanmon_cfgs(2);
1321         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1322         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1323         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1324         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1325
1326         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1327         let channel_reserve = chan_stat.channel_reserve_msat;
1328
1329         // The 2* and +1 are for the fee spike reserve.
1330         let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], chan.2), 1 + 1, get_opt_anchors!(nodes[0], chan.2));
1331         let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1332         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send + 1);
1333         let err = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).err().unwrap();
1334         match err {
1335                 PaymentSendFailure::AllFailedRetrySafe(ref fails) => {
1336                         match &fails[0] {
1337                                 &APIError::ChannelUnavailable{ref err} =>
1338                                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1339                                 _ => panic!("Unexpected error variant"),
1340                         }
1341                 },
1342                 _ => panic!("Unexpected error variant"),
1343         }
1344         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1345         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);
1346
1347         send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1348 }
1349
1350 #[test]
1351 fn test_fee_spike_violation_fails_htlc() {
1352         let chanmon_cfgs = create_chanmon_cfgs(2);
1353         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1354         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1355         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1356         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1357
1358         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3460001);
1359         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1360         let secp_ctx = Secp256k1::new();
1361         let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1362
1363         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1364
1365         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1366         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &Some(payment_secret), cur_height, &None).unwrap();
1367         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1368         let msg = msgs::UpdateAddHTLC {
1369                 channel_id: chan.2,
1370                 htlc_id: 0,
1371                 amount_msat: htlc_msat,
1372                 payment_hash: payment_hash,
1373                 cltv_expiry: htlc_cltv,
1374                 onion_routing_packet: onion_packet,
1375         };
1376
1377         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1378
1379         // Now manually create the commitment_signed message corresponding to the update_add
1380         // nodes[0] just sent. In the code for construction of this message, "local" refers
1381         // to the sender of the message, and "remote" refers to the receiver.
1382
1383         let feerate_per_kw = get_feerate!(nodes[0], chan.2);
1384
1385         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1386
1387         // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1388         // needed to sign the new commitment tx and (2) sign the new commitment tx.
1389         let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1390                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
1391                 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
1392                 let chan_signer = local_chan.get_signer();
1393                 // Make the signer believe we validated another commitment, so we can release the secret
1394                 chan_signer.get_enforcement_state().last_holder_commitment -= 1;
1395
1396                 let pubkeys = chan_signer.pubkeys();
1397                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1398                  chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1399                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1400                  chan_signer.pubkeys().funding_pubkey)
1401         };
1402         let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1403                 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
1404                 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
1405                 let chan_signer = remote_chan.get_signer();
1406                 let pubkeys = chan_signer.pubkeys();
1407                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1408                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1409                  chan_signer.pubkeys().funding_pubkey)
1410         };
1411
1412         // Assemble the set of keys we can use for signatures for our commitment_signed message.
1413         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1414                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
1415
1416         // Build the remote commitment transaction so we can sign it, and then later use the
1417         // signature for the commitment_signed message.
1418         let local_chan_balance = 1313;
1419
1420         let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1421                 offered: false,
1422                 amount_msat: 3460001,
1423                 cltv_expiry: htlc_cltv,
1424                 payment_hash,
1425                 transaction_output_index: Some(1),
1426         };
1427
1428         let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1429
1430         let res = {
1431                 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
1432                 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
1433                 let local_chan_signer = local_chan.get_signer();
1434                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1435                         commitment_number,
1436                         95000,
1437                         local_chan_balance,
1438                         local_chan.opt_anchors(), local_funding, remote_funding,
1439                         commit_tx_keys.clone(),
1440                         feerate_per_kw,
1441                         &mut vec![(accepted_htlc_info, ())],
1442                         &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1443                 );
1444                 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
1445         };
1446
1447         let commit_signed_msg = msgs::CommitmentSigned {
1448                 channel_id: chan.2,
1449                 signature: res.0,
1450                 htlc_signatures: res.1
1451         };
1452
1453         // Send the commitment_signed message to the nodes[1].
1454         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1455         let _ = nodes[1].node.get_and_clear_pending_msg_events();
1456
1457         // Send the RAA to nodes[1].
1458         let raa_msg = msgs::RevokeAndACK {
1459                 channel_id: chan.2,
1460                 per_commitment_secret: local_secret,
1461                 next_per_commitment_point: next_local_point
1462         };
1463         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1464
1465         let events = nodes[1].node.get_and_clear_pending_msg_events();
1466         assert_eq!(events.len(), 1);
1467         // Make sure the HTLC failed in the way we expect.
1468         match events[0] {
1469                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1470                         assert_eq!(update_fail_htlcs.len(), 1);
1471                         update_fail_htlcs[0].clone()
1472                 },
1473                 _ => panic!("Unexpected event"),
1474         };
1475         nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1476                 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", ::hex::encode(raa_msg.channel_id)), 1);
1477
1478         check_added_monitors!(nodes[1], 2);
1479 }
1480
1481 #[test]
1482 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1483         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1484         // Set the fee rate for the channel very high, to the point where the fundee
1485         // sending any above-dust amount would result in a channel reserve violation.
1486         // In this test we check that we would be prevented from sending an HTLC in
1487         // this situation.
1488         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1489         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1490         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1491         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1492         let default_config = UserConfig::default();
1493         let opt_anchors = false;
1494
1495         let mut push_amt = 100_000_000;
1496         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1497
1498         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1499
1500         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1501
1502         // Sending exactly enough to hit the reserve amount should be accepted
1503         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1504                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1505         }
1506
1507         // However one more HTLC should be significantly over the reserve amount and fail.
1508         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1509         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 },
1510                 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1511         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1512         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);
1513 }
1514
1515 #[test]
1516 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1517         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1518         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1519         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1520         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1521         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1522         let default_config = UserConfig::default();
1523         let opt_anchors = false;
1524
1525         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1526         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1527         // transaction fee with 0 HTLCs (183 sats)).
1528         let mut push_amt = 100_000_000;
1529         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1530         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1531         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1532
1533         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1534         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1535                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1536         }
1537
1538         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 700_000);
1539         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1540         let secp_ctx = Secp256k1::new();
1541         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1542         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1543         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1544         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 700_000, &Some(payment_secret), cur_height, &None).unwrap();
1545         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1546         let msg = msgs::UpdateAddHTLC {
1547                 channel_id: chan.2,
1548                 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1549                 amount_msat: htlc_msat,
1550                 payment_hash: payment_hash,
1551                 cltv_expiry: htlc_cltv,
1552                 onion_routing_packet: onion_packet,
1553         };
1554
1555         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1556         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1557         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);
1558         assert_eq!(nodes[0].node.list_channels().len(), 0);
1559         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1560         assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1561         check_added_monitors!(nodes[0], 1);
1562         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() });
1563 }
1564
1565 #[test]
1566 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1567         // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1568         // calculating our commitment transaction fee (this was previously broken).
1569         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1570         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1571
1572         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1573         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1574         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1575         let default_config = UserConfig::default();
1576         let opt_anchors = false;
1577
1578         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1579         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1580         // transaction fee with 0 HTLCs (183 sats)).
1581         let mut push_amt = 100_000_000;
1582         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1583         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1584         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1585
1586         let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1587                 + feerate_per_kw as u64 * htlc_success_tx_weight(opt_anchors) / 1000 * 1000 - 1;
1588         // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1589         // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1590         // commitment transaction fee.
1591         let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1592
1593         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1594         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1595                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1596         }
1597
1598         // One more than the dust amt should fail, however.
1599         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt + 1);
1600         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 },
1601                 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1602 }
1603
1604 #[test]
1605 fn test_chan_init_feerate_unaffordability() {
1606         // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to
1607         // channel reserve and feerate requirements.
1608         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1609         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1610         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1611         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1612         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1613         let default_config = UserConfig::default();
1614         let opt_anchors = false;
1615
1616         // Set the push_msat amount such that nodes[0] will not be able to afford to add even a single
1617         // HTLC.
1618         let mut push_amt = 100_000_000;
1619         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1620         assert_eq!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt + 1, 42, None).unwrap_err(),
1621                 APIError::APIMisuseError { err: "Funding amount (356) can't even pay fee for initial commitment transaction fee of 357.".to_string() });
1622
1623         // During open, we don't have a "counterparty channel reserve" to check against, so that
1624         // requirement only comes into play on the open_channel handling side.
1625         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1626         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt, 42, None).unwrap();
1627         let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
1628         open_channel_msg.push_msat += 1;
1629         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_channel_msg);
1630
1631         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1632         assert_eq!(msg_events.len(), 1);
1633         match msg_events[0] {
1634                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1635                         assert_eq!(msg.data, "Insufficient funding amount for initial reserve");
1636                 },
1637                 _ => panic!("Unexpected event"),
1638         }
1639 }
1640
1641 #[test]
1642 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1643         // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1644         // calculating our counterparty's commitment transaction fee (this was previously broken).
1645         let chanmon_cfgs = create_chanmon_cfgs(2);
1646         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1647         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1648         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1649         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1650
1651         let payment_amt = 46000; // Dust amount
1652         // In the previous code, these first four payments would succeed.
1653         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
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
1658         // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1659         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1660         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1661         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1662         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1663         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1664
1665         // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1666         // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1667         // transaction fee and therefore perceived this next payment as a channel reserve violation.
1668         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1669 }
1670
1671 #[test]
1672 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1673         let chanmon_cfgs = create_chanmon_cfgs(3);
1674         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1675         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1676         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1677         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1678         let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1679
1680         let feemsat = 239;
1681         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1682         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1683         let feerate = get_feerate!(nodes[0], chan.2);
1684         let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
1685
1686         // Add a 2* and +1 for the fee spike reserve.
1687         let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1688         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;
1689         let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1690
1691         // Add a pending HTLC.
1692         let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1693         let payment_event_1 = {
1694                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1695                 check_added_monitors!(nodes[0], 1);
1696
1697                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1698                 assert_eq!(events.len(), 1);
1699                 SendEvent::from_event(events.remove(0))
1700         };
1701         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1702
1703         // Attempt to trigger a channel reserve violation --> payment failure.
1704         let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2, opt_anchors);
1705         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;
1706         let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1707         let (route_2, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_2);
1708
1709         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1710         let secp_ctx = Secp256k1::new();
1711         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1712         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1713         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1714         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height, &None).unwrap();
1715         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1716         let msg = msgs::UpdateAddHTLC {
1717                 channel_id: chan.2,
1718                 htlc_id: 1,
1719                 amount_msat: htlc_msat + 1,
1720                 payment_hash: our_payment_hash_1,
1721                 cltv_expiry: htlc_cltv,
1722                 onion_routing_packet: onion_packet,
1723         };
1724
1725         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1726         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1727         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1728         assert_eq!(nodes[1].node.list_channels().len(), 1);
1729         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1730         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1731         check_added_monitors!(nodes[1], 1);
1732         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() });
1733 }
1734
1735 #[test]
1736 fn test_inbound_outbound_capacity_is_not_zero() {
1737         let chanmon_cfgs = create_chanmon_cfgs(2);
1738         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1739         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1740         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1741         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1742         let channels0 = node_chanmgrs[0].list_channels();
1743         let channels1 = node_chanmgrs[1].list_channels();
1744         let default_config = UserConfig::default();
1745         assert_eq!(channels0.len(), 1);
1746         assert_eq!(channels1.len(), 1);
1747
1748         let reserve = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config);
1749         assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1750         assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1751
1752         assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1753         assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1754 }
1755
1756 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64, opt_anchors: bool) -> u64 {
1757         (commitment_tx_base_weight(opt_anchors) + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1758 }
1759
1760 #[test]
1761 fn test_channel_reserve_holding_cell_htlcs() {
1762         let chanmon_cfgs = create_chanmon_cfgs(3);
1763         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1764         // When this test was written, the default base fee floated based on the HTLC count.
1765         // It is now fixed, so we simply set the fee to the expected value here.
1766         let mut config = test_default_channel_config();
1767         config.channel_config.forwarding_fee_base_msat = 239;
1768         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1769         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1770         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1771         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1772
1773         let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1774         let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1775
1776         let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1777         let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1778
1779         macro_rules! expect_forward {
1780                 ($node: expr) => {{
1781                         let mut events = $node.node.get_and_clear_pending_msg_events();
1782                         assert_eq!(events.len(), 1);
1783                         check_added_monitors!($node, 1);
1784                         let payment_event = SendEvent::from_event(events.remove(0));
1785                         payment_event
1786                 }}
1787         }
1788
1789         let feemsat = 239; // set above
1790         let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1791         let feerate = get_feerate!(nodes[0], chan_1.2);
1792         let opt_anchors = get_opt_anchors!(nodes[0], chan_1.2);
1793
1794         let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1795
1796         // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1797         {
1798                 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id())
1799                         .with_features(channelmanager::provided_invoice_features()).with_max_channel_saturation_power_of_half(0);
1800                 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);
1801                 route.paths[0].last_mut().unwrap().fee_msat += 1;
1802                 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1803
1804                 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 },
1805                         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)));
1806                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1807                 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);
1808         }
1809
1810         // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1811         // nodes[0]'s wealth
1812         loop {
1813                 let amt_msat = recv_value_0 + total_fee_msat;
1814                 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1815                 // Also, ensure that each payment has enough to be over the dust limit to
1816                 // ensure it'll be included in each commit tx fee calculation.
1817                 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1818                 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1819                 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1820                         break;
1821                 }
1822
1823                 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id())
1824                         .with_features(channelmanager::provided_invoice_features()).with_max_channel_saturation_power_of_half(0);
1825                 let route = get_route!(nodes[0], payment_params, recv_value_0, TEST_FINAL_CLTV).unwrap();
1826                 let (payment_preimage, ..) = send_along_route(&nodes[0], route, &[&nodes[1], &nodes[2]], recv_value_0);
1827                 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1828
1829                 let (stat01_, stat11_, stat12_, stat22_) = (
1830                         get_channel_value_stat!(nodes[0], chan_1.2),
1831                         get_channel_value_stat!(nodes[1], chan_1.2),
1832                         get_channel_value_stat!(nodes[1], chan_2.2),
1833                         get_channel_value_stat!(nodes[2], chan_2.2),
1834                 );
1835
1836                 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1837                 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1838                 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1839                 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1840                 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1841         }
1842
1843         // adding pending output.
1844         // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1845         // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1846         // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1847         // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1848         // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1849         // cases where 1 msat over X amount will cause a payment failure, but anything less than
1850         // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1851         // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1852         // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1853         // policy.
1854         let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1855         let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1856         let amt_msat_1 = recv_value_1 + total_fee_msat;
1857
1858         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);
1859         let payment_event_1 = {
1860                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1861                 check_added_monitors!(nodes[0], 1);
1862
1863                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1864                 assert_eq!(events.len(), 1);
1865                 SendEvent::from_event(events.remove(0))
1866         };
1867         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1868
1869         // channel reserve test with htlc pending output > 0
1870         let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1871         {
1872                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_2 + 1);
1873                 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 },
1874                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1875                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1876         }
1877
1878         // split the rest to test holding cell
1879         let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1880         let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1881         let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1882         let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1883         {
1884                 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
1885                 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);
1886         }
1887
1888         // now see if they go through on both sides
1889         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);
1890         // but this will stuck in the holding cell
1891         nodes[0].node.send_payment(&route_21, our_payment_hash_21, &Some(our_payment_secret_21), PaymentId(our_payment_hash_21.0)).unwrap();
1892         check_added_monitors!(nodes[0], 0);
1893         let events = nodes[0].node.get_and_clear_pending_events();
1894         assert_eq!(events.len(), 0);
1895
1896         // test with outbound holding cell amount > 0
1897         {
1898                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22+1);
1899                 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 },
1900                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1901                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1902                 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);
1903         }
1904
1905         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);
1906         // this will also stuck in the holding cell
1907         nodes[0].node.send_payment(&route_22, our_payment_hash_22, &Some(our_payment_secret_22), PaymentId(our_payment_hash_22.0)).unwrap();
1908         check_added_monitors!(nodes[0], 0);
1909         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1910         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1911
1912         // flush the pending htlc
1913         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1914         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1915         check_added_monitors!(nodes[1], 1);
1916
1917         // the pending htlc should be promoted to committed
1918         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1919         check_added_monitors!(nodes[0], 1);
1920         let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1921
1922         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1923         let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1924         // No commitment_signed so get_event_msg's assert(len == 1) passes
1925         check_added_monitors!(nodes[0], 1);
1926
1927         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1928         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1929         check_added_monitors!(nodes[1], 1);
1930
1931         expect_pending_htlcs_forwardable!(nodes[1]);
1932
1933         let ref payment_event_11 = expect_forward!(nodes[1]);
1934         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1935         commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1936
1937         expect_pending_htlcs_forwardable!(nodes[2]);
1938         expect_payment_received!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
1939
1940         // flush the htlcs in the holding cell
1941         assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1942         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1943         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1944         commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1945         expect_pending_htlcs_forwardable!(nodes[1]);
1946
1947         let ref payment_event_3 = expect_forward!(nodes[1]);
1948         assert_eq!(payment_event_3.msgs.len(), 2);
1949         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1950         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1951
1952         commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1953         expect_pending_htlcs_forwardable!(nodes[2]);
1954
1955         let events = nodes[2].node.get_and_clear_pending_events();
1956         assert_eq!(events.len(), 2);
1957         match events[0] {
1958                 Event::PaymentReceived { ref payment_hash, ref purpose, amount_msat } => {
1959                         assert_eq!(our_payment_hash_21, *payment_hash);
1960                         assert_eq!(recv_value_21, amount_msat);
1961                         match &purpose {
1962                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1963                                         assert!(payment_preimage.is_none());
1964                                         assert_eq!(our_payment_secret_21, *payment_secret);
1965                                 },
1966                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
1967                         }
1968                 },
1969                 _ => panic!("Unexpected event"),
1970         }
1971         match events[1] {
1972                 Event::PaymentReceived { ref payment_hash, ref purpose, amount_msat } => {
1973                         assert_eq!(our_payment_hash_22, *payment_hash);
1974                         assert_eq!(recv_value_22, amount_msat);
1975                         match &purpose {
1976                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1977                                         assert!(payment_preimage.is_none());
1978                                         assert_eq!(our_payment_secret_22, *payment_secret);
1979                                 },
1980                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
1981                         }
1982                 },
1983                 _ => panic!("Unexpected event"),
1984         }
1985
1986         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
1987         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
1988         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
1989
1990         let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1, opt_anchors);
1991         let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
1992         send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
1993
1994         let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
1995         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);
1996         let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
1997         assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
1998         assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
1999
2000         let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
2001         assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2002 }
2003
2004 #[test]
2005 fn channel_reserve_in_flight_removes() {
2006         // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2007         // can send to its counterparty, but due to update ordering, the other side may not yet have
2008         // considered those HTLCs fully removed.
2009         // This tests that we don't count HTLCs which will not be included in the next remote
2010         // commitment transaction towards the reserve value (as it implies no commitment transaction
2011         // will be generated which violates the remote reserve value).
2012         // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2013         // To test this we:
2014         //  * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2015         //    you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2016         //    you only consider the value of the first HTLC, it may not),
2017         //  * start routing a third HTLC from A to B,
2018         //  * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2019         //    the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2020         //  * deliver the first fulfill from B
2021         //  * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2022         //    claim,
2023         //  * deliver A's response CS and RAA.
2024         //    This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2025         //    removed it fully. B now has the push_msat plus the first two HTLCs in value.
2026         //  * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2027         //    of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2028         let chanmon_cfgs = create_chanmon_cfgs(2);
2029         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2030         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2031         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2032         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2033
2034         let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
2035         // Route the first two HTLCs.
2036         let payment_value_1 = b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000;
2037         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], payment_value_1);
2038         let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20_000);
2039
2040         // Start routing the third HTLC (this is just used to get everyone in the right state).
2041         let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
2042         let send_1 = {
2043                 nodes[0].node.send_payment(&route, payment_hash_3, &Some(payment_secret_3), PaymentId(payment_hash_3.0)).unwrap();
2044                 check_added_monitors!(nodes[0], 1);
2045                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2046                 assert_eq!(events.len(), 1);
2047                 SendEvent::from_event(events.remove(0))
2048         };
2049
2050         // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2051         // initial fulfill/CS.
2052         nodes[1].node.claim_funds(payment_preimage_1);
2053         expect_payment_claimed!(nodes[1], payment_hash_1, payment_value_1);
2054         check_added_monitors!(nodes[1], 1);
2055         let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2056
2057         // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2058         // remove the second HTLC when we send the HTLC back from B to A.
2059         nodes[1].node.claim_funds(payment_preimage_2);
2060         expect_payment_claimed!(nodes[1], payment_hash_2, 20_000);
2061         check_added_monitors!(nodes[1], 1);
2062         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2063
2064         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2065         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2066         check_added_monitors!(nodes[0], 1);
2067         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2068         expect_payment_sent_without_paths!(nodes[0], payment_preimage_1);
2069
2070         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2071         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2072         check_added_monitors!(nodes[1], 1);
2073         // B is already AwaitingRAA, so cant generate a CS here
2074         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2075
2076         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2077         check_added_monitors!(nodes[1], 1);
2078         let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2079
2080         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2081         check_added_monitors!(nodes[0], 1);
2082         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2083
2084         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2085         check_added_monitors!(nodes[1], 1);
2086         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2087
2088         // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2089         // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2090         // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2091         // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2092         // on-chain as necessary).
2093         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2094         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2095         check_added_monitors!(nodes[0], 1);
2096         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2097         expect_payment_sent_without_paths!(nodes[0], payment_preimage_2);
2098
2099         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2100         check_added_monitors!(nodes[1], 1);
2101         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2102
2103         expect_pending_htlcs_forwardable!(nodes[1]);
2104         expect_payment_received!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2105
2106         // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2107         // resolve the second HTLC from A's point of view.
2108         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2109         check_added_monitors!(nodes[0], 1);
2110         expect_payment_path_successful!(nodes[0]);
2111         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2112
2113         // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2114         // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2115         let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2116         let send_2 = {
2117                 nodes[1].node.send_payment(&route, payment_hash_4, &Some(payment_secret_4), PaymentId(payment_hash_4.0)).unwrap();
2118                 check_added_monitors!(nodes[1], 1);
2119                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2120                 assert_eq!(events.len(), 1);
2121                 SendEvent::from_event(events.remove(0))
2122         };
2123
2124         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2125         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2126         check_added_monitors!(nodes[0], 1);
2127         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2128
2129         // Now just resolve all the outstanding messages/HTLCs for completeness...
2130
2131         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2132         check_added_monitors!(nodes[1], 1);
2133         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2134
2135         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2136         check_added_monitors!(nodes[1], 1);
2137
2138         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2139         check_added_monitors!(nodes[0], 1);
2140         expect_payment_path_successful!(nodes[0]);
2141         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2142
2143         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2144         check_added_monitors!(nodes[1], 1);
2145         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2146
2147         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2148         check_added_monitors!(nodes[0], 1);
2149
2150         expect_pending_htlcs_forwardable!(nodes[0]);
2151         expect_payment_received!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2152
2153         claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2154         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2155 }
2156
2157 #[test]
2158 fn channel_monitor_network_test() {
2159         // Simple test which builds a network of ChannelManagers, connects them to each other, and
2160         // tests that ChannelMonitor is able to recover from various states.
2161         let chanmon_cfgs = create_chanmon_cfgs(5);
2162         let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2163         let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2164         let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2165
2166         // Create some initial channels
2167         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2168         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2169         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2170         let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2171
2172         // Make sure all nodes are at the same starting height
2173         connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2174         connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2175         connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2176         connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2177         connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2178
2179         // Rebalance the network a bit by relaying one payment through all the channels...
2180         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
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
2185         // Simple case with no pending HTLCs:
2186         nodes[1].node.force_close_broadcasting_latest_txn(&chan_1.2, &nodes[0].node.get_our_node_id()).unwrap();
2187         check_added_monitors!(nodes[1], 1);
2188         check_closed_broadcast!(nodes[1], true);
2189         {
2190                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2191                 assert_eq!(node_txn.len(), 1);
2192                 mine_transaction(&nodes[0], &node_txn[0]);
2193                 check_added_monitors!(nodes[0], 1);
2194                 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
2195         }
2196         check_closed_broadcast!(nodes[0], true);
2197         assert_eq!(nodes[0].node.list_channels().len(), 0);
2198         assert_eq!(nodes[1].node.list_channels().len(), 1);
2199         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2200         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2201
2202         // One pending HTLC is discarded by the force-close:
2203         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[1], &[&nodes[2], &nodes[3]], 3_000_000);
2204
2205         // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2206         // broadcasted until we reach the timelock time).
2207         nodes[1].node.force_close_broadcasting_latest_txn(&chan_2.2, &nodes[2].node.get_our_node_id()).unwrap();
2208         check_closed_broadcast!(nodes[1], true);
2209         check_added_monitors!(nodes[1], 1);
2210         {
2211                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2212                 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2213                 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2214                 mine_transaction(&nodes[2], &node_txn[0]);
2215                 check_added_monitors!(nodes[2], 1);
2216                 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
2217         }
2218         check_closed_broadcast!(nodes[2], true);
2219         assert_eq!(nodes[1].node.list_channels().len(), 0);
2220         assert_eq!(nodes[2].node.list_channels().len(), 1);
2221         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2222         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2223
2224         macro_rules! claim_funds {
2225                 ($node: expr, $prev_node: expr, $preimage: expr, $payment_hash: expr) => {
2226                         {
2227                                 $node.node.claim_funds($preimage);
2228                                 expect_payment_claimed!($node, $payment_hash, 3_000_000);
2229                                 check_added_monitors!($node, 1);
2230
2231                                 let events = $node.node.get_and_clear_pending_msg_events();
2232                                 assert_eq!(events.len(), 1);
2233                                 match events[0] {
2234                                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2235                                                 assert!(update_add_htlcs.is_empty());
2236                                                 assert!(update_fail_htlcs.is_empty());
2237                                                 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2238                                         },
2239                                         _ => panic!("Unexpected event"),
2240                                 };
2241                         }
2242                 }
2243         }
2244
2245         // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2246         // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2247         nodes[2].node.force_close_broadcasting_latest_txn(&chan_3.2, &nodes[3].node.get_our_node_id()).unwrap();
2248         check_added_monitors!(nodes[2], 1);
2249         check_closed_broadcast!(nodes[2], true);
2250         let node2_commitment_txid;
2251         {
2252                 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2253                 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2254                 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2255                 node2_commitment_txid = node_txn[0].txid();
2256
2257                 // Claim the payment on nodes[3], giving it knowledge of the preimage
2258                 claim_funds!(nodes[3], nodes[2], payment_preimage_1, payment_hash_1);
2259                 mine_transaction(&nodes[3], &node_txn[0]);
2260                 check_added_monitors!(nodes[3], 1);
2261                 check_preimage_claim(&nodes[3], &node_txn);
2262         }
2263         check_closed_broadcast!(nodes[3], true);
2264         assert_eq!(nodes[2].node.list_channels().len(), 0);
2265         assert_eq!(nodes[3].node.list_channels().len(), 1);
2266         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
2267         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2268
2269         // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2270         // confusing us in the following tests.
2271         let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2272
2273         // One pending HTLC to time out:
2274         let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[3], &[&nodes[4]], 3_000_000);
2275         // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2276         // buffer space).
2277
2278         let (close_chan_update_1, close_chan_update_2) = {
2279                 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2280                 let events = nodes[3].node.get_and_clear_pending_msg_events();
2281                 assert_eq!(events.len(), 2);
2282                 let close_chan_update_1 = match events[0] {
2283                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2284                                 msg.clone()
2285                         },
2286                         _ => panic!("Unexpected event"),
2287                 };
2288                 match events[1] {
2289                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2290                                 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2291                         },
2292                         _ => panic!("Unexpected event"),
2293                 }
2294                 check_added_monitors!(nodes[3], 1);
2295
2296                 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2297                 {
2298                         let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2299                         node_txn.retain(|tx| {
2300                                 if tx.input[0].previous_output.txid == node2_commitment_txid {
2301                                         false
2302                                 } else { true }
2303                         });
2304                 }
2305
2306                 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2307
2308                 // Claim the payment on nodes[4], giving it knowledge of the preimage
2309                 claim_funds!(nodes[4], nodes[3], payment_preimage_2, payment_hash_2);
2310
2311                 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2312                 let events = nodes[4].node.get_and_clear_pending_msg_events();
2313                 assert_eq!(events.len(), 2);
2314                 let close_chan_update_2 = match events[0] {
2315                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2316                                 msg.clone()
2317                         },
2318                         _ => panic!("Unexpected event"),
2319                 };
2320                 match events[1] {
2321                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2322                                 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2323                         },
2324                         _ => panic!("Unexpected event"),
2325                 }
2326                 check_added_monitors!(nodes[4], 1);
2327                 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2328
2329                 mine_transaction(&nodes[4], &node_txn[0]);
2330                 check_preimage_claim(&nodes[4], &node_txn);
2331                 (close_chan_update_1, close_chan_update_2)
2332         };
2333         nodes[3].gossip_sync.handle_channel_update(&close_chan_update_2).unwrap();
2334         nodes[4].gossip_sync.handle_channel_update(&close_chan_update_1).unwrap();
2335         assert_eq!(nodes[3].node.list_channels().len(), 0);
2336         assert_eq!(nodes[4].node.list_channels().len(), 0);
2337
2338         assert_eq!(nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon),
2339                 ChannelMonitorUpdateStatus::Completed);
2340         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2341         check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed);
2342 }
2343
2344 #[test]
2345 fn test_justice_tx() {
2346         // Test justice txn built on revoked HTLC-Success tx, against both sides
2347         let mut alice_config = UserConfig::default();
2348         alice_config.channel_handshake_config.announced_channel = true;
2349         alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2350         alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2351         let mut bob_config = UserConfig::default();
2352         bob_config.channel_handshake_config.announced_channel = true;
2353         bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2354         bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2355         let user_cfgs = [Some(alice_config), Some(bob_config)];
2356         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2357         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2358         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2359         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2360         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2361         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2362         *nodes[0].connect_style.borrow_mut() = ConnectStyle::FullBlockViaListen;
2363         // Create some new channels:
2364         let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2365
2366         // A pending HTLC which will be revoked:
2367         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2368         // Get the will-be-revoked local txn from nodes[0]
2369         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2370         assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2371         assert_eq!(revoked_local_txn[0].input.len(), 1);
2372         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2373         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2374         assert_eq!(revoked_local_txn[1].input.len(), 1);
2375         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2376         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2377         // Revoke the old state
2378         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2379
2380         {
2381                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2382                 {
2383                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2384                         assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2385                         assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2386
2387                         check_spends!(node_txn[0], revoked_local_txn[0]);
2388                         node_txn.swap_remove(0);
2389                         node_txn.truncate(1);
2390                 }
2391                 check_added_monitors!(nodes[1], 1);
2392                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2393                 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2394
2395                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2396                 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2397                 // Verify broadcast of revoked HTLC-timeout
2398                 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2399                 check_added_monitors!(nodes[0], 1);
2400                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2401                 // Broadcast revoked HTLC-timeout on node 1
2402                 mine_transaction(&nodes[1], &node_txn[1]);
2403                 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2404         }
2405         get_announce_close_broadcast_events(&nodes, 0, 1);
2406
2407         assert_eq!(nodes[0].node.list_channels().len(), 0);
2408         assert_eq!(nodes[1].node.list_channels().len(), 0);
2409
2410         // We test justice_tx build by A on B's revoked HTLC-Success tx
2411         // Create some new channels:
2412         let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2413         {
2414                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2415                 node_txn.clear();
2416         }
2417
2418         // A pending HTLC which will be revoked:
2419         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2420         // Get the will-be-revoked local txn from B
2421         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2422         assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2423         assert_eq!(revoked_local_txn[0].input.len(), 1);
2424         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2425         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2426         // Revoke the old state
2427         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2428         {
2429                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2430                 {
2431                         let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2432                         assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2433                         assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2434
2435                         check_spends!(node_txn[0], revoked_local_txn[0]);
2436                         node_txn.swap_remove(0);
2437                 }
2438                 check_added_monitors!(nodes[0], 1);
2439                 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2440
2441                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2442                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2443                 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2444                 check_added_monitors!(nodes[1], 1);
2445                 mine_transaction(&nodes[0], &node_txn[1]);
2446                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2447                 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2448         }
2449         get_announce_close_broadcast_events(&nodes, 0, 1);
2450         assert_eq!(nodes[0].node.list_channels().len(), 0);
2451         assert_eq!(nodes[1].node.list_channels().len(), 0);
2452 }
2453
2454 #[test]
2455 fn revoked_output_claim() {
2456         // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2457         // transaction is broadcast by its counterparty
2458         let chanmon_cfgs = create_chanmon_cfgs(2);
2459         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2460         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2461         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2462         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2463         // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2464         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2465         assert_eq!(revoked_local_txn.len(), 1);
2466         // Only output is the full channel value back to nodes[0]:
2467         assert_eq!(revoked_local_txn[0].output.len(), 1);
2468         // Send a payment through, updating everyone's latest commitment txn
2469         send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2470
2471         // Inform nodes[1] that nodes[0] broadcast a stale tx
2472         mine_transaction(&nodes[1], &revoked_local_txn[0]);
2473         check_added_monitors!(nodes[1], 1);
2474         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2475         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2476         assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2477
2478         check_spends!(node_txn[0], revoked_local_txn[0]);
2479         check_spends!(node_txn[1], chan_1.3);
2480
2481         // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2482         mine_transaction(&nodes[0], &revoked_local_txn[0]);
2483         get_announce_close_broadcast_events(&nodes, 0, 1);
2484         check_added_monitors!(nodes[0], 1);
2485         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2486 }
2487
2488 #[test]
2489 fn claim_htlc_outputs_shared_tx() {
2490         // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2491         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2492         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2493         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2494         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2495         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2496
2497         // Create some new channel:
2498         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2499
2500         // Rebalance the network to generate htlc in the two directions
2501         send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2502         // 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
2503         let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2504         let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2505
2506         // Get the will-be-revoked local txn from node[0]
2507         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2508         assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2509         assert_eq!(revoked_local_txn[0].input.len(), 1);
2510         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2511         assert_eq!(revoked_local_txn[1].input.len(), 1);
2512         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2513         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2514         check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2515
2516         //Revoke the old state
2517         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2518
2519         {
2520                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2521                 check_added_monitors!(nodes[0], 1);
2522                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2523                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2524                 check_added_monitors!(nodes[1], 1);
2525                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2526                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2527                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2528
2529                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2530                 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment
2531
2532                 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2533                 check_spends!(node_txn[0], revoked_local_txn[0]);
2534
2535                 let mut witness_lens = BTreeSet::new();
2536                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2537                 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2538                 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2539                 assert_eq!(witness_lens.len(), 3);
2540                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2541                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2542                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2543
2544                 // Next nodes[1] broadcasts its current local tx state:
2545                 assert_eq!(node_txn[1].input.len(), 1);
2546                 check_spends!(node_txn[1], chan_1.3);
2547
2548                 // Finally, mine the penalty transaction and check that we get an HTLC failure after
2549                 // ANTI_REORG_DELAY confirmations.
2550                 mine_transaction(&nodes[1], &node_txn[0]);
2551                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2552                 expect_payment_failed!(nodes[1], payment_hash_2, false);
2553         }
2554         get_announce_close_broadcast_events(&nodes, 0, 1);
2555         assert_eq!(nodes[0].node.list_channels().len(), 0);
2556         assert_eq!(nodes[1].node.list_channels().len(), 0);
2557 }
2558
2559 #[test]
2560 fn claim_htlc_outputs_single_tx() {
2561         // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2562         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2563         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2564         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2565         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2566         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2567
2568         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2569
2570         // Rebalance the network to generate htlc in the two directions
2571         send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2572         // 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
2573         // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2574         let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2575         let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2576
2577         // Get the will-be-revoked local txn from node[0]
2578         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2579
2580         //Revoke the old state
2581         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2582
2583         {
2584                 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2585                 check_added_monitors!(nodes[0], 1);
2586                 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2587                 check_added_monitors!(nodes[1], 1);
2588                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2589                 let mut events = nodes[0].node.get_and_clear_pending_events();
2590                 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2591                 match events.last().unwrap() {
2592                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2593                         _ => panic!("Unexpected event"),
2594                 }
2595
2596                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2597                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2598
2599                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2600                 assert!(node_txn.len() == 9 || node_txn.len() == 10);
2601
2602                 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2603                 assert_eq!(node_txn[0].input.len(), 1);
2604                 check_spends!(node_txn[0], chan_1.3);
2605                 assert_eq!(node_txn[1].input.len(), 1);
2606                 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2607                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2608                 check_spends!(node_txn[1], node_txn[0]);
2609
2610                 // Justice transactions are indices 1-2-4
2611                 assert_eq!(node_txn[2].input.len(), 1);
2612                 assert_eq!(node_txn[3].input.len(), 1);
2613                 assert_eq!(node_txn[4].input.len(), 1);
2614
2615                 check_spends!(node_txn[2], revoked_local_txn[0]);
2616                 check_spends!(node_txn[3], revoked_local_txn[0]);
2617                 check_spends!(node_txn[4], revoked_local_txn[0]);
2618
2619                 let mut witness_lens = BTreeSet::new();
2620                 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2621                 witness_lens.insert(node_txn[3].input[0].witness.last().unwrap().len());
2622                 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2623                 assert_eq!(witness_lens.len(), 3);
2624                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2625                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2626                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2627
2628                 // Finally, mine the penalty transactions and check that we get an HTLC failure after
2629                 // ANTI_REORG_DELAY confirmations.
2630                 mine_transaction(&nodes[1], &node_txn[2]);
2631                 mine_transaction(&nodes[1], &node_txn[3]);
2632                 mine_transaction(&nodes[1], &node_txn[4]);
2633                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2634                 expect_payment_failed!(nodes[1], payment_hash_2, false);
2635         }
2636         get_announce_close_broadcast_events(&nodes, 0, 1);
2637         assert_eq!(nodes[0].node.list_channels().len(), 0);
2638         assert_eq!(nodes[1].node.list_channels().len(), 0);
2639 }
2640
2641 #[test]
2642 fn test_htlc_on_chain_success() {
2643         // Test that in case of a unilateral close onchain, we detect the state of output and pass
2644         // the preimage backward accordingly. So here we test that ChannelManager is
2645         // broadcasting the right event to other nodes in payment path.
2646         // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2647         // A --------------------> B ----------------------> C (preimage)
2648         // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2649         // commitment transaction was broadcast.
2650         // Then, B should learn the preimage from said transactions, attempting to claim backwards
2651         // towards B.
2652         // B should be able to claim via preimage if A then broadcasts its local tx.
2653         // Finally, when A sees B's latest local commitment transaction it should be able to claim
2654         // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2655         // PaymentSent event).
2656
2657         let chanmon_cfgs = create_chanmon_cfgs(3);
2658         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2659         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2660         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2661
2662         // Create some initial channels
2663         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2664         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2665
2666         // Ensure all nodes are at the same height
2667         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2668         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2669         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2670         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2671
2672         // Rebalance the network a bit by relaying one payment through all the channels...
2673         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2674         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2675
2676         let (our_payment_preimage, payment_hash_1, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2677         let (our_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2678
2679         // Broadcast legit commitment tx from C on B's chain
2680         // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2681         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2682         assert_eq!(commitment_tx.len(), 1);
2683         check_spends!(commitment_tx[0], chan_2.3);
2684         nodes[2].node.claim_funds(our_payment_preimage);
2685         expect_payment_claimed!(nodes[2], payment_hash_1, 3_000_000);
2686         nodes[2].node.claim_funds(our_payment_preimage_2);
2687         expect_payment_claimed!(nodes[2], payment_hash_2, 3_000_000);
2688         check_added_monitors!(nodes[2], 2);
2689         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2690         assert!(updates.update_add_htlcs.is_empty());
2691         assert!(updates.update_fail_htlcs.is_empty());
2692         assert!(updates.update_fail_malformed_htlcs.is_empty());
2693         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2694
2695         mine_transaction(&nodes[2], &commitment_tx[0]);
2696         check_closed_broadcast!(nodes[2], true);
2697         check_added_monitors!(nodes[2], 1);
2698         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2699         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)
2700         assert_eq!(node_txn.len(), 5);
2701         assert_eq!(node_txn[0], node_txn[3]);
2702         assert_eq!(node_txn[1], node_txn[4]);
2703         assert_eq!(node_txn[2], commitment_tx[0]);
2704         check_spends!(node_txn[0], commitment_tx[0]);
2705         check_spends!(node_txn[1], commitment_tx[0]);
2706         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2707         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2708         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2709         assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2710         assert_eq!(node_txn[0].lock_time.0, 0);
2711         assert_eq!(node_txn[1].lock_time.0, 0);
2712
2713         // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2714         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
2715         connect_block(&nodes[1], &Block { header, txdata: node_txn});
2716         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2717         {
2718                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2719                 assert_eq!(added_monitors.len(), 1);
2720                 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2721                 added_monitors.clear();
2722         }
2723         let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2724         assert_eq!(forwarded_events.len(), 3);
2725         match forwarded_events[0] {
2726                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2727                 _ => panic!("Unexpected event"),
2728         }
2729         let chan_id = Some(chan_1.2);
2730         match forwarded_events[1] {
2731                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
2732                         assert_eq!(fee_earned_msat, Some(1000));
2733                         assert_eq!(prev_channel_id, chan_id);
2734                         assert_eq!(claim_from_onchain_tx, true);
2735                         assert_eq!(next_channel_id, Some(chan_2.2));
2736                 },
2737                 _ => panic!()
2738         }
2739         match forwarded_events[2] {
2740                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
2741                         assert_eq!(fee_earned_msat, Some(1000));
2742                         assert_eq!(prev_channel_id, chan_id);
2743                         assert_eq!(claim_from_onchain_tx, true);
2744                         assert_eq!(next_channel_id, Some(chan_2.2));
2745                 },
2746                 _ => panic!()
2747         }
2748         let events = nodes[1].node.get_and_clear_pending_msg_events();
2749         {
2750                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2751                 assert_eq!(added_monitors.len(), 2);
2752                 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2753                 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2754                 added_monitors.clear();
2755         }
2756         assert_eq!(events.len(), 3);
2757         match events[0] {
2758                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2759                 _ => panic!("Unexpected event"),
2760         }
2761         match events[1] {
2762                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2763                 _ => panic!("Unexpected event"),
2764         }
2765
2766         match events[2] {
2767                 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, .. } } => {
2768                         assert!(update_add_htlcs.is_empty());
2769                         assert!(update_fail_htlcs.is_empty());
2770                         assert_eq!(update_fulfill_htlcs.len(), 1);
2771                         assert!(update_fail_malformed_htlcs.is_empty());
2772                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2773                 },
2774                 _ => panic!("Unexpected event"),
2775         };
2776         macro_rules! check_tx_local_broadcast {
2777                 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2778                         let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2779                         assert_eq!(node_txn.len(), 3);
2780                         // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2781                         // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2782                         check_spends!(node_txn[1], $commitment_tx);
2783                         check_spends!(node_txn[2], $commitment_tx);
2784                         assert_ne!(node_txn[1].lock_time.0, 0);
2785                         assert_ne!(node_txn[2].lock_time.0, 0);
2786                         if $htlc_offered {
2787                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2788                                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2789                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2790                                 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2791                         } else {
2792                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2793                                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2794                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2795                                 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2796                         }
2797                         check_spends!(node_txn[0], $chan_tx);
2798                         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2799                         node_txn.clear();
2800                 } }
2801         }
2802         // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2803         // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2804         // timeout-claim of the output that nodes[2] just claimed via success.
2805         check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2806
2807         // Broadcast legit commitment tx from A on B's chain
2808         // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
2809         let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2810         check_spends!(node_a_commitment_tx[0], chan_1.3);
2811         mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2812         check_closed_broadcast!(nodes[1], true);
2813         check_added_monitors!(nodes[1], 1);
2814         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2815         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2816         assert_eq!(node_txn.len(), 6); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 3 (HTLC-Success, 2* RBF bumps of above HTLC txn)
2817         let commitment_spend =
2818                 if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2819                         check_spends!(node_txn[1], commitment_tx[0]);
2820                         check_spends!(node_txn[2], commitment_tx[0]);
2821                         assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2822                         &node_txn[0]
2823                 } else {
2824                         check_spends!(node_txn[0], commitment_tx[0]);
2825                         check_spends!(node_txn[1], commitment_tx[0]);
2826                         assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2827                         &node_txn[2]
2828                 };
2829
2830         check_spends!(commitment_spend, node_a_commitment_tx[0]);
2831         assert_eq!(commitment_spend.input.len(), 2);
2832         assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2833         assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2834         assert_eq!(commitment_spend.lock_time.0, 0);
2835         assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2836         check_spends!(node_txn[3], chan_1.3);
2837         assert_eq!(node_txn[3].input[0].witness.clone().last().unwrap().len(), 71);
2838         check_spends!(node_txn[4], node_txn[3]);
2839         check_spends!(node_txn[5], node_txn[3]);
2840         // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2841         // we already checked the same situation with A.
2842
2843         // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2844         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
2845         connect_block(&nodes[0], &Block { header, txdata: vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()] });
2846         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2847         check_closed_broadcast!(nodes[0], true);
2848         check_added_monitors!(nodes[0], 1);
2849         let events = nodes[0].node.get_and_clear_pending_events();
2850         assert_eq!(events.len(), 5);
2851         let mut first_claimed = false;
2852         for event in events {
2853                 match event {
2854                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
2855                                 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
2856                                         assert!(!first_claimed);
2857                                         first_claimed = true;
2858                                 } else {
2859                                         assert_eq!(payment_preimage, our_payment_preimage_2);
2860                                         assert_eq!(payment_hash, payment_hash_2);
2861                                 }
2862                         },
2863                         Event::PaymentPathSuccessful { .. } => {},
2864                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
2865                         _ => panic!("Unexpected event"),
2866                 }
2867         }
2868         check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0], chan_1.3);
2869 }
2870
2871 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2872         // Test that in case of a unilateral close onchain, we detect the state of output and
2873         // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2874         // broadcasting the right event to other nodes in payment path.
2875         // A ------------------> B ----------------------> C (timeout)
2876         //    B's commitment tx                 C's commitment tx
2877         //            \                                  \
2878         //         B's HTLC timeout tx               B's timeout tx
2879
2880         let chanmon_cfgs = create_chanmon_cfgs(3);
2881         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2882         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2883         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2884         *nodes[0].connect_style.borrow_mut() = connect_style;
2885         *nodes[1].connect_style.borrow_mut() = connect_style;
2886         *nodes[2].connect_style.borrow_mut() = connect_style;
2887
2888         // Create some intial channels
2889         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2890         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2891
2892         // Rebalance the network a bit by relaying one payment thorugh all the channels...
2893         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2894         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2895
2896         let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2897
2898         // Broadcast legit commitment tx from C on B's chain
2899         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2900         check_spends!(commitment_tx[0], chan_2.3);
2901         nodes[2].node.fail_htlc_backwards(&payment_hash);
2902         check_added_monitors!(nodes[2], 0);
2903         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }]);
2904         check_added_monitors!(nodes[2], 1);
2905
2906         let events = nodes[2].node.get_and_clear_pending_msg_events();
2907         assert_eq!(events.len(), 1);
2908         match events[0] {
2909                 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, .. } } => {
2910                         assert!(update_add_htlcs.is_empty());
2911                         assert!(!update_fail_htlcs.is_empty());
2912                         assert!(update_fulfill_htlcs.is_empty());
2913                         assert!(update_fail_malformed_htlcs.is_empty());
2914                         assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2915                 },
2916                 _ => panic!("Unexpected event"),
2917         };
2918         mine_transaction(&nodes[2], &commitment_tx[0]);
2919         check_closed_broadcast!(nodes[2], true);
2920         check_added_monitors!(nodes[2], 1);
2921         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2922         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2923         assert_eq!(node_txn.len(), 1);
2924         check_spends!(node_txn[0], chan_2.3);
2925         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2926
2927         // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2928         // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2929         connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2930         mine_transaction(&nodes[1], &commitment_tx[0]);
2931         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2932         let timeout_tx;
2933         {
2934                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2935                 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
2936                 assert_eq!(node_txn[0], node_txn[3]);
2937                 assert_eq!(node_txn[1], node_txn[4]);
2938
2939                 check_spends!(node_txn[2], commitment_tx[0]);
2940                 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2941
2942                 check_spends!(node_txn[0], chan_2.3);
2943                 check_spends!(node_txn[1], node_txn[0]);
2944                 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2945                 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2946
2947                 timeout_tx = node_txn[2].clone();
2948                 node_txn.clear();
2949         }
2950
2951         mine_transaction(&nodes[1], &timeout_tx);
2952         check_added_monitors!(nodes[1], 1);
2953         check_closed_broadcast!(nodes[1], true);
2954         {
2955                 // B will rebroadcast a fee-bumped timeout transaction here.
2956                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2957                 assert_eq!(node_txn.len(), 1);
2958                 check_spends!(node_txn[0], commitment_tx[0]);
2959         }
2960
2961         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2962         {
2963                 // B may rebroadcast its own holder commitment transaction here, as a safeguard against
2964                 // some incredibly unlikely partial-eclipse-attack scenarios. That said, because the
2965                 // original commitment_tx[0] (also spending chan_2.3) has reached ANTI_REORG_DELAY B really
2966                 // shouldn't broadcast anything here, and in some connect style scenarios we do not.
2967                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2968                 if node_txn.len() == 1 {
2969                         check_spends!(node_txn[0], chan_2.3);
2970                 } else {
2971                         assert_eq!(node_txn.len(), 0);
2972                 }
2973         }
2974
2975         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 }]);
2976         check_added_monitors!(nodes[1], 1);
2977         let events = nodes[1].node.get_and_clear_pending_msg_events();
2978         assert_eq!(events.len(), 1);
2979         match events[0] {
2980                 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, .. } } => {
2981                         assert!(update_add_htlcs.is_empty());
2982                         assert!(!update_fail_htlcs.is_empty());
2983                         assert!(update_fulfill_htlcs.is_empty());
2984                         assert!(update_fail_malformed_htlcs.is_empty());
2985                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2986                 },
2987                 _ => panic!("Unexpected event"),
2988         };
2989
2990         // Broadcast legit commitment tx from B on A's chain
2991         let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
2992         check_spends!(commitment_tx[0], chan_1.3);
2993
2994         mine_transaction(&nodes[0], &commitment_tx[0]);
2995         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2996
2997         check_closed_broadcast!(nodes[0], true);
2998         check_added_monitors!(nodes[0], 1);
2999         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
3000         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 commitment tx, ChannelMonitor : 1 timeout tx
3001         assert_eq!(node_txn.len(), 2);
3002         check_spends!(node_txn[0], chan_1.3);
3003         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
3004         check_spends!(node_txn[1], commitment_tx[0]);
3005         assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3006 }
3007
3008 #[test]
3009 fn test_htlc_on_chain_timeout() {
3010         do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
3011         do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
3012         do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
3013 }
3014
3015 #[test]
3016 fn test_simple_commitment_revoked_fail_backward() {
3017         // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3018         // and fail backward accordingly.
3019
3020         let chanmon_cfgs = create_chanmon_cfgs(3);
3021         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3022         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3023         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3024
3025         // Create some initial channels
3026         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3027         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3028
3029         let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3030         // Get the will-be-revoked local txn from nodes[2]
3031         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3032         // Revoke the old state
3033         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3034
3035         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3036
3037         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3038         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3039         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3040         check_added_monitors!(nodes[1], 1);
3041         check_closed_broadcast!(nodes[1], true);
3042
3043         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 }]);
3044         check_added_monitors!(nodes[1], 1);
3045         let events = nodes[1].node.get_and_clear_pending_msg_events();
3046         assert_eq!(events.len(), 1);
3047         match events[0] {
3048                 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, ref commitment_signed, .. } } => {
3049                         assert!(update_add_htlcs.is_empty());
3050                         assert_eq!(update_fail_htlcs.len(), 1);
3051                         assert!(update_fulfill_htlcs.is_empty());
3052                         assert!(update_fail_malformed_htlcs.is_empty());
3053                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3054
3055                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3056                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3057                         expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3058                 },
3059                 _ => panic!("Unexpected event"),
3060         }
3061 }
3062
3063 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3064         // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3065         // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3066         // commitment transaction anymore.
3067         // To do this, we have the peer which will broadcast a revoked commitment transaction send
3068         // a number of update_fail/commitment_signed updates without ever sending the RAA in
3069         // response to our commitment_signed. This is somewhat misbehavior-y, though not
3070         // technically disallowed and we should probably handle it reasonably.
3071         // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3072         // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3073         // transactions:
3074         // * Once we move it out of our holding cell/add it, we will immediately include it in a
3075         //   commitment_signed (implying it will be in the latest remote commitment transaction).
3076         // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3077         //   and once they revoke the previous commitment transaction (allowing us to send a new
3078         //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3079         let chanmon_cfgs = create_chanmon_cfgs(3);
3080         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3081         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3082         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3083
3084         // Create some initial channels
3085         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3086         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3087
3088         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 });
3089         // Get the will-be-revoked local txn from nodes[2]
3090         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3091         assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3092         // Revoke the old state
3093         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3094
3095         let value = if use_dust {
3096                 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3097                 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3098                 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3099         } else { 3000000 };
3100
3101         let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3102         let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3103         let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3104
3105         nodes[2].node.fail_htlc_backwards(&first_payment_hash);
3106         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
3107         check_added_monitors!(nodes[2], 1);
3108         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3109         assert!(updates.update_add_htlcs.is_empty());
3110         assert!(updates.update_fulfill_htlcs.is_empty());
3111         assert!(updates.update_fail_malformed_htlcs.is_empty());
3112         assert_eq!(updates.update_fail_htlcs.len(), 1);
3113         assert!(updates.update_fee.is_none());
3114         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3115         let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3116         // Drop the last RAA from 3 -> 2
3117
3118         nodes[2].node.fail_htlc_backwards(&second_payment_hash);
3119         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: second_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         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3129         check_added_monitors!(nodes[1], 1);
3130         // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3131         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3132         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3133         check_added_monitors!(nodes[2], 1);
3134
3135         nodes[2].node.fail_htlc_backwards(&third_payment_hash);
3136         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: third_payment_hash }]);
3137         check_added_monitors!(nodes[2], 1);
3138         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3139         assert!(updates.update_add_htlcs.is_empty());
3140         assert!(updates.update_fulfill_htlcs.is_empty());
3141         assert!(updates.update_fail_malformed_htlcs.is_empty());
3142         assert_eq!(updates.update_fail_htlcs.len(), 1);
3143         assert!(updates.update_fee.is_none());
3144         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3145         // At this point first_payment_hash has dropped out of the latest two commitment
3146         // transactions that nodes[1] is tracking...
3147         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3148         check_added_monitors!(nodes[1], 1);
3149         // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3150         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3151         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3152         check_added_monitors!(nodes[2], 1);
3153
3154         // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3155         // on nodes[2]'s RAA.
3156         let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3157         nodes[1].node.send_payment(&route, fourth_payment_hash, &Some(fourth_payment_secret), PaymentId(fourth_payment_hash.0)).unwrap();
3158         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3159         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3160         check_added_monitors!(nodes[1], 0);
3161
3162         if deliver_bs_raa {
3163                 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3164                 // One monitor for the new revocation preimage, no second on as we won't generate a new
3165                 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3166                 check_added_monitors!(nodes[1], 1);
3167                 let events = nodes[1].node.get_and_clear_pending_events();
3168                 assert_eq!(events.len(), 2);
3169                 match events[0] {
3170                         Event::PendingHTLCsForwardable { .. } => { },
3171                         _ => panic!("Unexpected event"),
3172                 };
3173                 match events[1] {
3174                         Event::HTLCHandlingFailed { .. } => { },
3175                         _ => panic!("Unexpected event"),
3176                 }
3177                 // Deliberately don't process the pending fail-back so they all fail back at once after
3178                 // block connection just like the !deliver_bs_raa case
3179         }
3180
3181         let mut failed_htlcs = HashSet::new();
3182         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3183
3184         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3185         check_added_monitors!(nodes[1], 1);
3186         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3187
3188         let events = nodes[1].node.get_and_clear_pending_events();
3189         assert_eq!(events.len(), if deliver_bs_raa { 2 + nodes.len() - 1 } else { 3 + nodes.len() });
3190         match events[0] {
3191                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3192                 _ => panic!("Unexepected event"),
3193         }
3194         match events[1] {
3195                 Event::PaymentPathFailed { ref payment_hash, .. } => {
3196                         assert_eq!(*payment_hash, fourth_payment_hash);
3197                 },
3198                 _ => panic!("Unexpected event"),
3199         }
3200         if !deliver_bs_raa {
3201                 match events[2] {
3202                         Event::PendingHTLCsForwardable { .. } => { },
3203                         _ => panic!("Unexpected event"),
3204                 };
3205                 nodes[1].node.abandon_payment(PaymentId(fourth_payment_hash.0));
3206                 let payment_failed_events = nodes[1].node.get_and_clear_pending_events();
3207                 assert_eq!(payment_failed_events.len(), 1);
3208                 match payment_failed_events[0] {
3209                         Event::PaymentFailed { ref payment_hash, .. } => {
3210                                 assert_eq!(*payment_hash, fourth_payment_hash);
3211                         },
3212                         _ => panic!("Unexpected event"),
3213                 }
3214         }
3215         nodes[1].node.process_pending_htlc_forwards();
3216         check_added_monitors!(nodes[1], 1);
3217
3218         let events = nodes[1].node.get_and_clear_pending_msg_events();
3219         assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3220         match events[if deliver_bs_raa { 1 } else { 0 }] {
3221                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3222                 _ => panic!("Unexpected event"),
3223         }
3224         match events[if deliver_bs_raa { 2 } else { 1 }] {
3225                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3226                         assert_eq!(channel_id, chan_2.2);
3227                         assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3228                 },
3229                 _ => panic!("Unexpected event"),
3230         }
3231         if deliver_bs_raa {
3232                 match events[0] {
3233                         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, .. } } => {
3234                                 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3235                                 assert_eq!(update_add_htlcs.len(), 1);
3236                                 assert!(update_fulfill_htlcs.is_empty());
3237                                 assert!(update_fail_htlcs.is_empty());
3238                                 assert!(update_fail_malformed_htlcs.is_empty());
3239                         },
3240                         _ => panic!("Unexpected event"),
3241                 }
3242         }
3243         match events[if deliver_bs_raa { 3 } else { 2 }] {
3244                 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, .. } } => {
3245                         assert!(update_add_htlcs.is_empty());
3246                         assert_eq!(update_fail_htlcs.len(), 3);
3247                         assert!(update_fulfill_htlcs.is_empty());
3248                         assert!(update_fail_malformed_htlcs.is_empty());
3249                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3250
3251                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3252                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3253                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3254
3255                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3256
3257                         let events = nodes[0].node.get_and_clear_pending_events();
3258                         assert_eq!(events.len(), 3);
3259                         match events[0] {
3260                                 Event::PaymentPathFailed { ref payment_hash, ref network_update, .. } => {
3261                                         assert!(failed_htlcs.insert(payment_hash.0));
3262                                         // If we delivered B's RAA we got an unknown preimage error, not something
3263                                         // that we should update our routing table for.
3264                                         if !deliver_bs_raa {
3265                                                 assert!(network_update.is_some());
3266                                         }
3267                                 },
3268                                 _ => panic!("Unexpected event"),
3269                         }
3270                         match events[1] {
3271                                 Event::PaymentPathFailed { ref payment_hash, ref network_update, .. } => {
3272                                         assert!(failed_htlcs.insert(payment_hash.0));
3273                                         assert!(network_update.is_some());
3274                                 },
3275                                 _ => panic!("Unexpected event"),
3276                         }
3277                         match events[2] {
3278                                 Event::PaymentPathFailed { ref payment_hash, ref network_update, .. } => {
3279                                         assert!(failed_htlcs.insert(payment_hash.0));
3280                                         assert!(network_update.is_some());
3281                                 },
3282                                 _ => panic!("Unexpected event"),
3283                         }
3284                 },
3285                 _ => panic!("Unexpected event"),
3286         }
3287
3288         assert!(failed_htlcs.contains(&first_payment_hash.0));
3289         assert!(failed_htlcs.contains(&second_payment_hash.0));
3290         assert!(failed_htlcs.contains(&third_payment_hash.0));
3291 }
3292
3293 #[test]
3294 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3295         do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3296         do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3297         do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3298         do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3299 }
3300
3301 #[test]
3302 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3303         do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3304         do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3305         do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3306         do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3307 }
3308
3309 #[test]
3310 fn fail_backward_pending_htlc_upon_channel_failure() {
3311         let chanmon_cfgs = create_chanmon_cfgs(2);
3312         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3313         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3314         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3315         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());
3316
3317         // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3318         {
3319                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3320                 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
3321                 check_added_monitors!(nodes[0], 1);
3322
3323                 let payment_event = {
3324                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3325                         assert_eq!(events.len(), 1);
3326                         SendEvent::from_event(events.remove(0))
3327                 };
3328                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3329                 assert_eq!(payment_event.msgs.len(), 1);
3330         }
3331
3332         // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3333         let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3334         {
3335                 nodes[0].node.send_payment(&route, failed_payment_hash, &Some(failed_payment_secret), PaymentId(failed_payment_hash.0)).unwrap();
3336                 check_added_monitors!(nodes[0], 0);
3337
3338                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3339         }
3340
3341         // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3342         {
3343                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3344
3345                 let secp_ctx = Secp256k1::new();
3346                 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3347                 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3348                 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &Some(payment_secret), current_height, &None).unwrap();
3349                 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3350                 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3351
3352                 // Send a 0-msat update_add_htlc to fail the channel.
3353                 let update_add_htlc = msgs::UpdateAddHTLC {
3354                         channel_id: chan.2,
3355                         htlc_id: 0,
3356                         amount_msat: 0,
3357                         payment_hash,
3358                         cltv_expiry,
3359                         onion_routing_packet,
3360                 };
3361                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3362         }
3363         let events = nodes[0].node.get_and_clear_pending_events();
3364         assert_eq!(events.len(), 2);
3365         // Check that Alice fails backward the pending HTLC from the second payment.
3366         match events[0] {
3367                 Event::PaymentPathFailed { payment_hash, .. } => {
3368                         assert_eq!(payment_hash, failed_payment_hash);
3369                 },
3370                 _ => panic!("Unexpected event"),
3371         }
3372         match events[1] {
3373                 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3374                         assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3375                 },
3376                 _ => panic!("Unexpected event {:?}", events[1]),
3377         }
3378         check_closed_broadcast!(nodes[0], true);
3379         check_added_monitors!(nodes[0], 1);
3380 }
3381
3382 #[test]
3383 fn test_htlc_ignore_latest_remote_commitment() {
3384         // Test that HTLC transactions spending the latest remote commitment transaction are simply
3385         // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3386         let chanmon_cfgs = create_chanmon_cfgs(2);
3387         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3388         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3389         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3390         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3391
3392         route_payment(&nodes[0], &[&nodes[1]], 10000000);
3393         nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3394         connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3395         check_closed_broadcast!(nodes[0], true);
3396         check_added_monitors!(nodes[0], 1);
3397         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
3398
3399         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3400         assert_eq!(node_txn.len(), 3);
3401         assert_eq!(node_txn[0], node_txn[1]);
3402
3403         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
3404         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3405         check_closed_broadcast!(nodes[1], true);
3406         check_added_monitors!(nodes[1], 1);
3407         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3408
3409         // Duplicate the connect_block call since this may happen due to other listeners
3410         // registering new transactions
3411         header.prev_blockhash = header.block_hash();
3412         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[2].clone()]});
3413 }
3414
3415 #[test]
3416 fn test_force_close_fail_back() {
3417         // Check which HTLCs are failed-backwards on channel force-closure
3418         let chanmon_cfgs = create_chanmon_cfgs(3);
3419         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3420         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3421         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3422         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3423         create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3424
3425         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3426
3427         let mut payment_event = {
3428                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
3429                 check_added_monitors!(nodes[0], 1);
3430
3431                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3432                 assert_eq!(events.len(), 1);
3433                 SendEvent::from_event(events.remove(0))
3434         };
3435
3436         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3437         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3438
3439         expect_pending_htlcs_forwardable!(nodes[1]);
3440
3441         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3442         assert_eq!(events_2.len(), 1);
3443         payment_event = SendEvent::from_event(events_2.remove(0));
3444         assert_eq!(payment_event.msgs.len(), 1);
3445
3446         check_added_monitors!(nodes[1], 1);
3447         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3448         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3449         check_added_monitors!(nodes[2], 1);
3450         let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3451
3452         // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3453         // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3454         // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3455
3456         nodes[2].node.force_close_broadcasting_latest_txn(&payment_event.commitment_msg.channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3457         check_closed_broadcast!(nodes[2], true);
3458         check_added_monitors!(nodes[2], 1);
3459         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
3460         let tx = {
3461                 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3462                 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3463                 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3464                 // back to nodes[1] upon timeout otherwise.
3465                 assert_eq!(node_txn.len(), 1);
3466                 node_txn.remove(0)
3467         };
3468
3469         mine_transaction(&nodes[1], &tx);
3470
3471         // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3472         check_closed_broadcast!(nodes[1], true);
3473         check_added_monitors!(nodes[1], 1);
3474         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3475
3476         // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3477         {
3478                 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3479                         .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);
3480         }
3481         mine_transaction(&nodes[2], &tx);
3482         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3483         assert_eq!(node_txn.len(), 1);
3484         assert_eq!(node_txn[0].input.len(), 1);
3485         assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3486         assert_eq!(node_txn[0].lock_time.0, 0); // Must be an HTLC-Success
3487         assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3488
3489         check_spends!(node_txn[0], tx);
3490 }
3491
3492 #[test]
3493 fn test_dup_events_on_peer_disconnect() {
3494         // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3495         // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3496         // as we used to generate the event immediately upon receipt of the payment preimage in the
3497         // update_fulfill_htlc message.
3498
3499         let chanmon_cfgs = create_chanmon_cfgs(2);
3500         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3501         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3502         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3503         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3504
3505         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3506
3507         nodes[1].node.claim_funds(payment_preimage);
3508         expect_payment_claimed!(nodes[1], payment_hash, 1_000_000);
3509         check_added_monitors!(nodes[1], 1);
3510         let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3511         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3512         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
3513
3514         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3515         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3516
3517         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3518         expect_payment_path_successful!(nodes[0]);
3519 }
3520
3521 #[test]
3522 fn test_peer_disconnected_before_funding_broadcasted() {
3523         // Test that channels are closed with `ClosureReason::DisconnectedPeer` if the peer disconnects
3524         // before the funding transaction has been broadcasted.
3525         let chanmon_cfgs = create_chanmon_cfgs(2);
3526         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3527         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3528         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3529
3530         // Open a channel between `nodes[0]` and `nodes[1]`, for which the funding transaction is never
3531         // broadcasted, even though it's created by `nodes[0]`.
3532         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();
3533         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
3534         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_channel);
3535         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
3536         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_channel);
3537
3538         let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
3539         assert_eq!(temporary_channel_id, expected_temporary_channel_id);
3540
3541         assert!(nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
3542
3543         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
3544         assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
3545
3546         // Even though the funding transaction is created by `nodes[0]`, the `FundingCreated` msg is
3547         // never sent to `nodes[1]`, and therefore the tx is never signed by either party nor
3548         // broadcasted.
3549         {
3550                 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
3551         }
3552
3553         // Ensure that the channel is closed with `ClosureReason::DisconnectedPeer` when the peers are
3554         // disconnected before the funding transaction was broadcasted.
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
3558         check_closed_event!(nodes[0], 1, ClosureReason::DisconnectedPeer);
3559         check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
3560 }
3561
3562 #[test]
3563 fn test_simple_peer_disconnect() {
3564         // Test that we can reconnect when there are no lost messages
3565         let chanmon_cfgs = create_chanmon_cfgs(3);
3566         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3567         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3568         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3569         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3570         create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3571
3572         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3573         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3574         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3575
3576         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3577         let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3578         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3579         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3580
3581         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3582         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3583         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3584
3585         let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3586         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3587         let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3588         let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3589
3590         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3591         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3592
3593         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3594         fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3595
3596         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3597         {
3598                 let events = nodes[0].node.get_and_clear_pending_events();
3599                 assert_eq!(events.len(), 3);
3600                 match events[0] {
3601                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3602                                 assert_eq!(payment_preimage, payment_preimage_3);
3603                                 assert_eq!(payment_hash, payment_hash_3);
3604                         },
3605                         _ => panic!("Unexpected event"),
3606                 }
3607                 match events[1] {
3608                         Event::PaymentPathFailed { payment_hash, payment_failed_permanently, .. } => {
3609                                 assert_eq!(payment_hash, payment_hash_5);
3610                                 assert!(payment_failed_permanently);
3611                         },
3612                         _ => panic!("Unexpected event"),
3613                 }
3614                 match events[2] {
3615                         Event::PaymentPathSuccessful { .. } => {},
3616                         _ => panic!("Unexpected event"),
3617                 }
3618         }
3619
3620         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3621         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3622 }
3623
3624 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3625         // Test that we can reconnect when in-flight HTLC updates get dropped
3626         let chanmon_cfgs = create_chanmon_cfgs(2);
3627         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3628         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3629         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3630
3631         let mut as_channel_ready = None;
3632         if messages_delivered == 0 {
3633                 let (channel_ready, _, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3634                 as_channel_ready = Some(channel_ready);
3635                 // nodes[1] doesn't receive the channel_ready message (it'll be re-sent on reconnect)
3636                 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3637                 // it before the channel_reestablish message.
3638         } else {
3639                 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3640         }
3641
3642         let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1_000_000);
3643
3644         let payment_event = {
3645                 nodes[0].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
3646                 check_added_monitors!(nodes[0], 1);
3647
3648                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3649                 assert_eq!(events.len(), 1);
3650                 SendEvent::from_event(events.remove(0))
3651         };
3652         assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3653
3654         if messages_delivered < 2 {
3655                 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3656         } else {
3657                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3658                 if messages_delivered >= 3 {
3659                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3660                         check_added_monitors!(nodes[1], 1);
3661                         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3662
3663                         if messages_delivered >= 4 {
3664                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3665                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3666                                 check_added_monitors!(nodes[0], 1);
3667
3668                                 if messages_delivered >= 5 {
3669                                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3670                                         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3671                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3672                                         check_added_monitors!(nodes[0], 1);
3673
3674                                         if messages_delivered >= 6 {
3675                                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3676                                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3677                                                 check_added_monitors!(nodes[1], 1);
3678                                         }
3679                                 }
3680                         }
3681                 }
3682         }
3683
3684         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3685         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3686         if messages_delivered < 3 {
3687                 if simulate_broken_lnd {
3688                         // lnd has a long-standing bug where they send a channel_ready prior to a
3689                         // channel_reestablish if you reconnect prior to channel_ready time.
3690                         //
3691                         // Here we simulate that behavior, delivering a channel_ready immediately on
3692                         // reconnect. Note that we don't bother skipping the now-duplicate channel_ready sent
3693                         // in `reconnect_nodes` but we currently don't fail based on that.
3694                         //
3695                         // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3696                         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready.as_ref().unwrap().0);
3697                 }
3698                 // Even if the channel_ready messages get exchanged, as long as nothing further was
3699                 // received on either side, both sides will need to resend them.
3700                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3701         } else if messages_delivered == 3 {
3702                 // nodes[0] still wants its RAA + commitment_signed
3703                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3704         } else if messages_delivered == 4 {
3705                 // nodes[0] still wants its commitment_signed
3706                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3707         } else if messages_delivered == 5 {
3708                 // nodes[1] still wants its final RAA
3709                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3710         } else if messages_delivered == 6 {
3711                 // Everything was delivered...
3712                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3713         }
3714
3715         let events_1 = nodes[1].node.get_and_clear_pending_events();
3716         assert_eq!(events_1.len(), 1);
3717         match events_1[0] {
3718                 Event::PendingHTLCsForwardable { .. } => { },
3719                 _ => panic!("Unexpected event"),
3720         };
3721
3722         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3723         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3724         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3725
3726         nodes[1].node.process_pending_htlc_forwards();
3727
3728         let events_2 = nodes[1].node.get_and_clear_pending_events();
3729         assert_eq!(events_2.len(), 1);
3730         match events_2[0] {
3731                 Event::PaymentReceived { ref payment_hash, ref purpose, amount_msat } => {
3732                         assert_eq!(payment_hash_1, *payment_hash);
3733                         assert_eq!(amount_msat, 1_000_000);
3734                         match &purpose {
3735                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3736                                         assert!(payment_preimage.is_none());
3737                                         assert_eq!(payment_secret_1, *payment_secret);
3738                                 },
3739                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
3740                         }
3741                 },
3742                 _ => panic!("Unexpected event"),
3743         }
3744
3745         nodes[1].node.claim_funds(payment_preimage_1);
3746         check_added_monitors!(nodes[1], 1);
3747         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3748
3749         let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3750         assert_eq!(events_3.len(), 1);
3751         let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3752                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3753                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3754                         assert!(updates.update_add_htlcs.is_empty());
3755                         assert!(updates.update_fail_htlcs.is_empty());
3756                         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3757                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3758                         assert!(updates.update_fee.is_none());
3759                         (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3760                 },
3761                 _ => panic!("Unexpected event"),
3762         };
3763
3764         if messages_delivered >= 1 {
3765                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3766
3767                 let events_4 = nodes[0].node.get_and_clear_pending_events();
3768                 assert_eq!(events_4.len(), 1);
3769                 match events_4[0] {
3770                         Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3771                                 assert_eq!(payment_preimage_1, *payment_preimage);
3772                                 assert_eq!(payment_hash_1, *payment_hash);
3773                         },
3774                         _ => panic!("Unexpected event"),
3775                 }
3776
3777                 if messages_delivered >= 2 {
3778                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3779                         check_added_monitors!(nodes[0], 1);
3780                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3781
3782                         if messages_delivered >= 3 {
3783                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3784                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3785                                 check_added_monitors!(nodes[1], 1);
3786
3787                                 if messages_delivered >= 4 {
3788                                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3789                                         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3790                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3791                                         check_added_monitors!(nodes[1], 1);
3792
3793                                         if messages_delivered >= 5 {
3794                                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3795                                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3796                                                 check_added_monitors!(nodes[0], 1);
3797                                         }
3798                                 }
3799                         }
3800                 }
3801         }
3802
3803         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3804         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3805         if messages_delivered < 2 {
3806                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3807                 if messages_delivered < 1 {
3808                         expect_payment_sent!(nodes[0], payment_preimage_1);
3809                 } else {
3810                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3811                 }
3812         } else if messages_delivered == 2 {
3813                 // nodes[0] still wants its RAA + commitment_signed
3814                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3815         } else if messages_delivered == 3 {
3816                 // nodes[0] still wants its commitment_signed
3817                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3818         } else if messages_delivered == 4 {
3819                 // nodes[1] still wants its final RAA
3820                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3821         } else if messages_delivered == 5 {
3822                 // Everything was delivered...
3823                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3824         }
3825
3826         if messages_delivered == 1 || messages_delivered == 2 {
3827                 expect_payment_path_successful!(nodes[0]);
3828         }
3829
3830         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3831         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3832         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3833
3834         if messages_delivered > 2 {
3835                 expect_payment_path_successful!(nodes[0]);
3836         }
3837
3838         // Channel should still work fine...
3839         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3840         let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3841         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3842 }
3843
3844 #[test]
3845 fn test_drop_messages_peer_disconnect_a() {
3846         do_test_drop_messages_peer_disconnect(0, true);
3847         do_test_drop_messages_peer_disconnect(0, false);
3848         do_test_drop_messages_peer_disconnect(1, false);
3849         do_test_drop_messages_peer_disconnect(2, false);
3850 }
3851
3852 #[test]
3853 fn test_drop_messages_peer_disconnect_b() {
3854         do_test_drop_messages_peer_disconnect(3, false);
3855         do_test_drop_messages_peer_disconnect(4, false);
3856         do_test_drop_messages_peer_disconnect(5, false);
3857         do_test_drop_messages_peer_disconnect(6, false);
3858 }
3859
3860 #[test]
3861 fn test_funding_peer_disconnect() {
3862         // Test that we can lock in our funding tx while disconnected
3863         let chanmon_cfgs = create_chanmon_cfgs(2);
3864         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3865         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3866         let persister: test_utils::TestPersister;
3867         let new_chain_monitor: test_utils::TestChainMonitor;
3868         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
3869         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3870         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3871
3872         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3873         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3874
3875         confirm_transaction(&nodes[0], &tx);
3876         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3877         assert!(events_1.is_empty());
3878
3879         reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3880
3881         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3882         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3883
3884         confirm_transaction(&nodes[1], &tx);
3885         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3886         assert!(events_2.is_empty());
3887
3888         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
3889         let as_reestablish = get_chan_reestablish_msgs!(nodes[0], nodes[1]).pop().unwrap();
3890         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
3891         let bs_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]).pop().unwrap();
3892
3893         // nodes[0] hasn't yet received a channel_ready, so it only sends that on reconnect.
3894         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
3895         let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3896         assert_eq!(events_3.len(), 1);
3897         let as_channel_ready = match events_3[0] {
3898                 MessageSendEvent::SendChannelReady { ref node_id, ref msg } => {
3899                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3900                         msg.clone()
3901                 },
3902                 _ => panic!("Unexpected event {:?}", events_3[0]),
3903         };
3904
3905         // nodes[1] received nodes[0]'s channel_ready on the first reconnect above, so it should send
3906         // announcement_signatures as well as channel_update.
3907         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reestablish);
3908         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3909         assert_eq!(events_4.len(), 3);
3910         let chan_id;
3911         let bs_channel_ready = match events_4[0] {
3912                 MessageSendEvent::SendChannelReady { ref node_id, ref msg } => {
3913                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3914                         chan_id = msg.channel_id;
3915                         msg.clone()
3916                 },
3917                 _ => panic!("Unexpected event {:?}", events_4[0]),
3918         };
3919         let bs_announcement_sigs = match events_4[1] {
3920                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3921                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3922                         msg.clone()
3923                 },
3924                 _ => panic!("Unexpected event {:?}", events_4[1]),
3925         };
3926         match events_4[2] {
3927                 MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } => {
3928                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3929                 },
3930                 _ => panic!("Unexpected event {:?}", events_4[2]),
3931         }
3932
3933         // Re-deliver nodes[0]'s channel_ready, which nodes[1] can safely ignore. It currently
3934         // generates a duplicative private channel_update
3935         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
3936         let events_5 = nodes[1].node.get_and_clear_pending_msg_events();
3937         assert_eq!(events_5.len(), 1);
3938         match events_5[0] {
3939                 MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } => {
3940                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3941                 },
3942                 _ => panic!("Unexpected event {:?}", events_5[0]),
3943         };
3944
3945         // When we deliver nodes[1]'s channel_ready, however, nodes[0] will generate its
3946         // announcement_signatures.
3947         nodes[0].node.handle_channel_ready(&nodes[1].node.get_our_node_id(), &bs_channel_ready);
3948         let events_6 = nodes[0].node.get_and_clear_pending_msg_events();
3949         assert_eq!(events_6.len(), 1);
3950         let as_announcement_sigs = match events_6[0] {
3951                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3952                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3953                         msg.clone()
3954                 },
3955                 _ => panic!("Unexpected event {:?}", events_6[0]),
3956         };
3957
3958         // When we deliver nodes[1]'s announcement_signatures to nodes[0], nodes[0] should immediately
3959         // broadcast the channel announcement globally, as well as re-send its (now-public)
3960         // channel_update.
3961         nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3962         let events_7 = nodes[0].node.get_and_clear_pending_msg_events();
3963         assert_eq!(events_7.len(), 1);
3964         let (chan_announcement, as_update) = match events_7[0] {
3965                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3966                         (msg.clone(), update_msg.clone())
3967                 },
3968                 _ => panic!("Unexpected event {:?}", events_7[0]),
3969         };
3970
3971         // Finally, deliver nodes[0]'s announcement_signatures to nodes[1] and make sure it creates the
3972         // same channel_announcement.
3973         nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3974         let events_8 = nodes[1].node.get_and_clear_pending_msg_events();
3975         assert_eq!(events_8.len(), 1);
3976         let bs_update = match events_8[0] {
3977                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3978                         assert_eq!(*msg, chan_announcement);
3979                         update_msg.clone()
3980                 },
3981                 _ => panic!("Unexpected event {:?}", events_8[0]),
3982         };
3983
3984         // Provide the channel announcement and public updates to the network graph
3985         nodes[0].gossip_sync.handle_channel_announcement(&chan_announcement).unwrap();
3986         nodes[0].gossip_sync.handle_channel_update(&bs_update).unwrap();
3987         nodes[0].gossip_sync.handle_channel_update(&as_update).unwrap();
3988
3989         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3990         let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3991         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
3992
3993         // Check that after deserialization and reconnection we can still generate an identical
3994         // channel_announcement from the cached signatures.
3995         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3996
3997         let nodes_0_serialized = nodes[0].node.encode();
3998         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
3999         get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
4000
4001         persister = test_utils::TestPersister::new();
4002         let keys_manager = &chanmon_cfgs[0].keys_manager;
4003         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);
4004         nodes[0].chain_monitor = &new_chain_monitor;
4005         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4006         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4007                 &mut chan_0_monitor_read, keys_manager).unwrap();
4008         assert!(chan_0_monitor_read.is_empty());
4009
4010         let mut nodes_0_read = &nodes_0_serialized[..];
4011         let (_, nodes_0_deserialized_tmp) = {
4012                 let mut channel_monitors = HashMap::new();
4013                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4014                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4015                         default_config: UserConfig::default(),
4016                         keys_manager,
4017                         fee_estimator: node_cfgs[0].fee_estimator,
4018                         chain_monitor: nodes[0].chain_monitor,
4019                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4020                         logger: nodes[0].logger,
4021                         channel_monitors,
4022                 }).unwrap()
4023         };
4024         nodes_0_deserialized = nodes_0_deserialized_tmp;
4025         assert!(nodes_0_read.is_empty());
4026
4027         assert_eq!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor),
4028                 ChannelMonitorUpdateStatus::Completed);
4029         nodes[0].node = &nodes_0_deserialized;
4030         check_added_monitors!(nodes[0], 1);
4031
4032         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4033 }
4034
4035 #[test]
4036 fn test_channel_ready_without_best_block_updated() {
4037         // Previously, if we were offline when a funding transaction was locked in, and then we came
4038         // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
4039         // generate a channel_ready until a later best_block_updated. This tests that we generate the
4040         // channel_ready immediately instead.
4041         let chanmon_cfgs = create_chanmon_cfgs(2);
4042         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4043         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4044         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4045         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
4046
4047         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());
4048
4049         let conf_height = nodes[0].best_block_info().1 + 1;
4050         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
4051         let block_txn = [funding_tx];
4052         let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
4053         let conf_block_header = nodes[0].get_block_header(conf_height);
4054         nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
4055
4056         // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
4057         let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
4058         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
4059 }
4060
4061 #[test]
4062 fn test_drop_messages_peer_disconnect_dual_htlc() {
4063         // Test that we can handle reconnecting when both sides of a channel have pending
4064         // commitment_updates when we disconnect.
4065         let chanmon_cfgs = create_chanmon_cfgs(2);
4066         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4067         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4068         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4069         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4070
4071         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
4072
4073         // Now try to send a second payment which will fail to send
4074         let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
4075         nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
4076         check_added_monitors!(nodes[0], 1);
4077
4078         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
4079         assert_eq!(events_1.len(), 1);
4080         match events_1[0] {
4081                 MessageSendEvent::UpdateHTLCs { .. } => {},
4082                 _ => panic!("Unexpected event"),
4083         }
4084
4085         nodes[1].node.claim_funds(payment_preimage_1);
4086         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
4087         check_added_monitors!(nodes[1], 1);
4088
4089         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
4090         assert_eq!(events_2.len(), 1);
4091         match events_2[0] {
4092                 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 } } => {
4093                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
4094                         assert!(update_add_htlcs.is_empty());
4095                         assert_eq!(update_fulfill_htlcs.len(), 1);
4096                         assert!(update_fail_htlcs.is_empty());
4097                         assert!(update_fail_malformed_htlcs.is_empty());
4098                         assert!(update_fee.is_none());
4099
4100                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
4101                         let events_3 = nodes[0].node.get_and_clear_pending_events();
4102                         assert_eq!(events_3.len(), 1);
4103                         match events_3[0] {
4104                                 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4105                                         assert_eq!(*payment_preimage, payment_preimage_1);
4106                                         assert_eq!(*payment_hash, payment_hash_1);
4107                                 },
4108                                 _ => panic!("Unexpected event"),
4109                         }
4110
4111                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
4112                         let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4113                         // No commitment_signed so get_event_msg's assert(len == 1) passes
4114                         check_added_monitors!(nodes[0], 1);
4115                 },
4116                 _ => panic!("Unexpected event"),
4117         }
4118
4119         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
4120         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4121
4122         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
4123         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4124         assert_eq!(reestablish_1.len(), 1);
4125         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
4126         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4127         assert_eq!(reestablish_2.len(), 1);
4128
4129         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4130         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4131         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4132         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4133
4134         assert!(as_resp.0.is_none());
4135         assert!(bs_resp.0.is_none());
4136
4137         assert!(bs_resp.1.is_none());
4138         assert!(bs_resp.2.is_none());
4139
4140         assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4141
4142         assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4143         assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4144         assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4145         assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4146         assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4147         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4148         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4149         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4150         // No commitment_signed so get_event_msg's assert(len == 1) passes
4151         check_added_monitors!(nodes[1], 1);
4152
4153         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4154         let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4155         assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4156         assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4157         assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4158         assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4159         assert!(bs_second_commitment_signed.update_fee.is_none());
4160         check_added_monitors!(nodes[1], 1);
4161
4162         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4163         let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4164         assert!(as_commitment_signed.update_add_htlcs.is_empty());
4165         assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4166         assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4167         assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4168         assert!(as_commitment_signed.update_fee.is_none());
4169         check_added_monitors!(nodes[0], 1);
4170
4171         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4172         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4173         // No commitment_signed so get_event_msg's assert(len == 1) passes
4174         check_added_monitors!(nodes[0], 1);
4175
4176         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4177         let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4178         // No commitment_signed so get_event_msg's assert(len == 1) passes
4179         check_added_monitors!(nodes[1], 1);
4180
4181         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4182         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4183         check_added_monitors!(nodes[1], 1);
4184
4185         expect_pending_htlcs_forwardable!(nodes[1]);
4186
4187         let events_5 = nodes[1].node.get_and_clear_pending_events();
4188         assert_eq!(events_5.len(), 1);
4189         match events_5[0] {
4190                 Event::PaymentReceived { ref payment_hash, ref purpose, .. } => {
4191                         assert_eq!(payment_hash_2, *payment_hash);
4192                         match &purpose {
4193                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4194                                         assert!(payment_preimage.is_none());
4195                                         assert_eq!(payment_secret_2, *payment_secret);
4196                                 },
4197                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
4198                         }
4199                 },
4200                 _ => panic!("Unexpected event"),
4201         }
4202
4203         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4204         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4205         check_added_monitors!(nodes[0], 1);
4206
4207         expect_payment_path_successful!(nodes[0]);
4208         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4209 }
4210
4211 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4212         // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4213         // to avoid our counterparty failing the channel.
4214         let chanmon_cfgs = create_chanmon_cfgs(2);
4215         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4216         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4217         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4218
4219         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4220
4221         let our_payment_hash = if send_partial_mpp {
4222                 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4223                 // Use the utility function send_payment_along_path to send the payment with MPP data which
4224                 // indicates there are more HTLCs coming.
4225                 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.
4226                 let payment_id = PaymentId([42; 32]);
4227                 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash, Some(payment_secret), payment_id, &route).unwrap();
4228                 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();
4229                 check_added_monitors!(nodes[0], 1);
4230                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4231                 assert_eq!(events.len(), 1);
4232                 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4233                 // hop should *not* yet generate any PaymentReceived event(s).
4234                 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4235                 our_payment_hash
4236         } else {
4237                 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4238         };
4239
4240         let mut block = Block {
4241                 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
4242                 txdata: vec![],
4243         };
4244         connect_block(&nodes[0], &block);
4245         connect_block(&nodes[1], &block);
4246         let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4247         for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4248                 block.header.prev_blockhash = block.block_hash();
4249                 connect_block(&nodes[0], &block);
4250                 connect_block(&nodes[1], &block);
4251         }
4252
4253         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
4254
4255         check_added_monitors!(nodes[1], 1);
4256         let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4257         assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4258         assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4259         assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4260         assert!(htlc_timeout_updates.update_fee.is_none());
4261
4262         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4263         commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4264         // 100_000 msat as u64, followed by the height at which we failed back above
4265         let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
4266         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(block_count - 1));
4267         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4268 }
4269
4270 #[test]
4271 fn test_htlc_timeout() {
4272         do_test_htlc_timeout(true);
4273         do_test_htlc_timeout(false);
4274 }
4275
4276 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4277         // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4278         let chanmon_cfgs = create_chanmon_cfgs(3);
4279         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4280         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4281         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4282         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4283         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4284
4285         // Make sure all nodes are at the same starting height
4286         connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4287         connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4288         connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4289
4290         // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4291         let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4292         {
4293                 nodes[1].node.send_payment(&route, first_payment_hash, &Some(first_payment_secret), PaymentId(first_payment_hash.0)).unwrap();
4294         }
4295         assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4296         check_added_monitors!(nodes[1], 1);
4297
4298         // Now attempt to route a second payment, which should be placed in the holding cell
4299         let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4300         let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4301         sending_node.node.send_payment(&route, second_payment_hash, &Some(second_payment_secret), PaymentId(second_payment_hash.0)).unwrap();
4302         if forwarded_htlc {
4303                 check_added_monitors!(nodes[0], 1);
4304                 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4305                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4306                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4307                 expect_pending_htlcs_forwardable!(nodes[1]);
4308         }
4309         check_added_monitors!(nodes[1], 0);
4310
4311         connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4312         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4313         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4314         connect_blocks(&nodes[1], 1);
4315
4316         if forwarded_htlc {
4317                 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 }]);
4318                 check_added_monitors!(nodes[1], 1);
4319                 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4320                 assert_eq!(fail_commit.len(), 1);
4321                 match fail_commit[0] {
4322                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4323                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4324                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4325                         },
4326                         _ => unreachable!(),
4327                 }
4328                 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4329         } else {
4330                 expect_payment_failed!(nodes[1], second_payment_hash, false);
4331         }
4332 }
4333
4334 #[test]
4335 fn test_holding_cell_htlc_add_timeouts() {
4336         do_test_holding_cell_htlc_add_timeouts(false);
4337         do_test_holding_cell_htlc_add_timeouts(true);
4338 }
4339
4340 #[test]
4341 fn test_no_txn_manager_serialize_deserialize() {
4342         let chanmon_cfgs = create_chanmon_cfgs(2);
4343         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4344         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4345         let logger: test_utils::TestLogger;
4346         let fee_estimator: test_utils::TestFeeEstimator;
4347         let persister: test_utils::TestPersister;
4348         let new_chain_monitor: test_utils::TestChainMonitor;
4349         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4350         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4351
4352         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4353
4354         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4355
4356         let nodes_0_serialized = nodes[0].node.encode();
4357         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4358         get_monitor!(nodes[0], OutPoint { txid: tx.txid(), index: 0 }.to_channel_id())
4359                 .write(&mut chan_0_monitor_serialized).unwrap();
4360
4361         logger = test_utils::TestLogger::new();
4362         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4363         persister = test_utils::TestPersister::new();
4364         let keys_manager = &chanmon_cfgs[0].keys_manager;
4365         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4366         nodes[0].chain_monitor = &new_chain_monitor;
4367         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4368         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4369                 &mut chan_0_monitor_read, keys_manager).unwrap();
4370         assert!(chan_0_monitor_read.is_empty());
4371
4372         let mut nodes_0_read = &nodes_0_serialized[..];
4373         let config = UserConfig::default();
4374         let (_, nodes_0_deserialized_tmp) = {
4375                 let mut channel_monitors = HashMap::new();
4376                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4377                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4378                         default_config: config,
4379                         keys_manager,
4380                         fee_estimator: &fee_estimator,
4381                         chain_monitor: nodes[0].chain_monitor,
4382                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4383                         logger: &logger,
4384                         channel_monitors,
4385                 }).unwrap()
4386         };
4387         nodes_0_deserialized = nodes_0_deserialized_tmp;
4388         assert!(nodes_0_read.is_empty());
4389
4390         assert_eq!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor),
4391                 ChannelMonitorUpdateStatus::Completed);
4392         nodes[0].node = &nodes_0_deserialized;
4393         assert_eq!(nodes[0].node.list_channels().len(), 1);
4394         check_added_monitors!(nodes[0], 1);
4395
4396         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
4397         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4398         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
4399         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4400
4401         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4402         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4403         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4404         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4405
4406         let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4407         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
4408         for node in nodes.iter() {
4409                 assert!(node.gossip_sync.handle_channel_announcement(&announcement).unwrap());
4410                 node.gossip_sync.handle_channel_update(&as_update).unwrap();
4411                 node.gossip_sync.handle_channel_update(&bs_update).unwrap();
4412         }
4413
4414         send_payment(&nodes[0], &[&nodes[1]], 1000000);
4415 }
4416
4417 #[test]
4418 fn test_manager_serialize_deserialize_events() {
4419         // This test makes sure the events field in ChannelManager survives de/serialization
4420         let chanmon_cfgs = create_chanmon_cfgs(2);
4421         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4422         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4423         let fee_estimator: test_utils::TestFeeEstimator;
4424         let persister: test_utils::TestPersister;
4425         let logger: test_utils::TestLogger;
4426         let new_chain_monitor: test_utils::TestChainMonitor;
4427         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4428         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4429
4430         // Start creating a channel, but stop right before broadcasting the funding transaction
4431         let channel_value = 100000;
4432         let push_msat = 10001;
4433         let a_flags = channelmanager::provided_init_features();
4434         let b_flags = channelmanager::provided_init_features();
4435         let node_a = nodes.remove(0);
4436         let node_b = nodes.remove(0);
4437         node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
4438         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()));
4439         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()));
4440
4441         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, &node_b.node.get_our_node_id(), channel_value, 42);
4442
4443         node_a.node.funding_transaction_generated(&temporary_channel_id, &node_b.node.get_our_node_id(), tx.clone()).unwrap();
4444         check_added_monitors!(node_a, 0);
4445
4446         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()));
4447         {
4448                 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
4449                 assert_eq!(added_monitors.len(), 1);
4450                 assert_eq!(added_monitors[0].0, funding_output);
4451                 added_monitors.clear();
4452         }
4453
4454         let bs_funding_signed = get_event_msg!(node_b, MessageSendEvent::SendFundingSigned, node_a.node.get_our_node_id());
4455         node_a.node.handle_funding_signed(&node_b.node.get_our_node_id(), &bs_funding_signed);
4456         {
4457                 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
4458                 assert_eq!(added_monitors.len(), 1);
4459                 assert_eq!(added_monitors[0].0, funding_output);
4460                 added_monitors.clear();
4461         }
4462         // Normally, this is where node_a would broadcast the funding transaction, but the test de/serializes first instead
4463
4464         nodes.push(node_a);
4465         nodes.push(node_b);
4466
4467         // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4468         let nodes_0_serialized = nodes[0].node.encode();
4469         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4470         get_monitor!(nodes[0], bs_funding_signed.channel_id).write(&mut chan_0_monitor_serialized).unwrap();
4471
4472         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4473         logger = test_utils::TestLogger::new();
4474         persister = test_utils::TestPersister::new();
4475         let keys_manager = &chanmon_cfgs[0].keys_manager;
4476         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4477         nodes[0].chain_monitor = &new_chain_monitor;
4478         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4479         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4480                 &mut chan_0_monitor_read, keys_manager).unwrap();
4481         assert!(chan_0_monitor_read.is_empty());
4482
4483         let mut nodes_0_read = &nodes_0_serialized[..];
4484         let config = UserConfig::default();
4485         let (_, nodes_0_deserialized_tmp) = {
4486                 let mut channel_monitors = HashMap::new();
4487                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4488                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4489                         default_config: config,
4490                         keys_manager,
4491                         fee_estimator: &fee_estimator,
4492                         chain_monitor: nodes[0].chain_monitor,
4493                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4494                         logger: &logger,
4495                         channel_monitors,
4496                 }).unwrap()
4497         };
4498         nodes_0_deserialized = nodes_0_deserialized_tmp;
4499         assert!(nodes_0_read.is_empty());
4500
4501         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4502
4503         assert_eq!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor),
4504                 ChannelMonitorUpdateStatus::Completed);
4505         nodes[0].node = &nodes_0_deserialized;
4506
4507         // After deserializing, make sure the funding_transaction is still held by the channel manager
4508         let events_4 = nodes[0].node.get_and_clear_pending_events();
4509         assert_eq!(events_4.len(), 0);
4510         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
4511         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
4512
4513         // Make sure the channel is functioning as though the de/serialization never happened
4514         assert_eq!(nodes[0].node.list_channels().len(), 1);
4515         check_added_monitors!(nodes[0], 1);
4516
4517         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
4518         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4519         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
4520         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4521
4522         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4523         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4524         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4525         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4526
4527         let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4528         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
4529         for node in nodes.iter() {
4530                 assert!(node.gossip_sync.handle_channel_announcement(&announcement).unwrap());
4531                 node.gossip_sync.handle_channel_update(&as_update).unwrap();
4532                 node.gossip_sync.handle_channel_update(&bs_update).unwrap();
4533         }
4534
4535         send_payment(&nodes[0], &[&nodes[1]], 1000000);
4536 }
4537
4538 #[test]
4539 fn test_simple_manager_serialize_deserialize() {
4540         let chanmon_cfgs = create_chanmon_cfgs(2);
4541         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4542         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4543         let logger: test_utils::TestLogger;
4544         let fee_estimator: test_utils::TestFeeEstimator;
4545         let persister: test_utils::TestPersister;
4546         let new_chain_monitor: test_utils::TestChainMonitor;
4547         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4548         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4549         let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
4550
4551         let (our_payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4552         let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4553
4554         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4555
4556         let nodes_0_serialized = nodes[0].node.encode();
4557         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4558         get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
4559
4560         logger = test_utils::TestLogger::new();
4561         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4562         persister = test_utils::TestPersister::new();
4563         let keys_manager = &chanmon_cfgs[0].keys_manager;
4564         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4565         nodes[0].chain_monitor = &new_chain_monitor;
4566         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4567         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4568                 &mut chan_0_monitor_read, keys_manager).unwrap();
4569         assert!(chan_0_monitor_read.is_empty());
4570
4571         let mut nodes_0_read = &nodes_0_serialized[..];
4572         let (_, nodes_0_deserialized_tmp) = {
4573                 let mut channel_monitors = HashMap::new();
4574                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4575                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4576                         default_config: UserConfig::default(),
4577                         keys_manager,
4578                         fee_estimator: &fee_estimator,
4579                         chain_monitor: nodes[0].chain_monitor,
4580                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4581                         logger: &logger,
4582                         channel_monitors,
4583                 }).unwrap()
4584         };
4585         nodes_0_deserialized = nodes_0_deserialized_tmp;
4586         assert!(nodes_0_read.is_empty());
4587
4588         assert_eq!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor),
4589                 ChannelMonitorUpdateStatus::Completed);
4590         nodes[0].node = &nodes_0_deserialized;
4591         check_added_monitors!(nodes[0], 1);
4592
4593         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4594
4595         fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4596         claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
4597 }
4598
4599 #[test]
4600 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4601         // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4602         let chanmon_cfgs = create_chanmon_cfgs(4);
4603         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4604         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4605         let logger: test_utils::TestLogger;
4606         let fee_estimator: test_utils::TestFeeEstimator;
4607         let persister: test_utils::TestPersister;
4608         let new_chain_monitor: test_utils::TestChainMonitor;
4609         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4610         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4611         let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
4612         let chan_id_2 = create_announced_chan_between_nodes(&nodes, 2, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
4613         let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4614
4615         let mut node_0_stale_monitors_serialized = Vec::new();
4616         for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4617                 let mut writer = test_utils::TestVecWriter(Vec::new());
4618                 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4619                 node_0_stale_monitors_serialized.push(writer.0);
4620         }
4621
4622         let (our_payment_preimage, _, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4623
4624         // Serialize the ChannelManager here, but the monitor we keep up-to-date
4625         let nodes_0_serialized = nodes[0].node.encode();
4626
4627         route_payment(&nodes[0], &[&nodes[3]], 1000000);
4628         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4629         nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4630         nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4631
4632         // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4633         // nodes[3])
4634         let mut node_0_monitors_serialized = Vec::new();
4635         for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4636                 let mut writer = test_utils::TestVecWriter(Vec::new());
4637                 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4638                 node_0_monitors_serialized.push(writer.0);
4639         }
4640
4641         logger = test_utils::TestLogger::new();
4642         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4643         persister = test_utils::TestPersister::new();
4644         let keys_manager = &chanmon_cfgs[0].keys_manager;
4645         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4646         nodes[0].chain_monitor = &new_chain_monitor;
4647
4648
4649         let mut node_0_stale_monitors = Vec::new();
4650         for serialized in node_0_stale_monitors_serialized.iter() {
4651                 let mut read = &serialized[..];
4652                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4653                 assert!(read.is_empty());
4654                 node_0_stale_monitors.push(monitor);
4655         }
4656
4657         let mut node_0_monitors = Vec::new();
4658         for serialized in node_0_monitors_serialized.iter() {
4659                 let mut read = &serialized[..];
4660                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4661                 assert!(read.is_empty());
4662                 node_0_monitors.push(monitor);
4663         }
4664
4665         let mut nodes_0_read = &nodes_0_serialized[..];
4666         if let Err(msgs::DecodeError::InvalidValue) =
4667                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4668                 default_config: UserConfig::default(),
4669                 keys_manager,
4670                 fee_estimator: &fee_estimator,
4671                 chain_monitor: nodes[0].chain_monitor,
4672                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4673                 logger: &logger,
4674                 channel_monitors: node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4675         }) { } else {
4676                 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4677         };
4678
4679         let mut nodes_0_read = &nodes_0_serialized[..];
4680         let (_, nodes_0_deserialized_tmp) =
4681                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4682                 default_config: UserConfig::default(),
4683                 keys_manager,
4684                 fee_estimator: &fee_estimator,
4685                 chain_monitor: nodes[0].chain_monitor,
4686                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4687                 logger: &logger,
4688                 channel_monitors: node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4689         }).unwrap();
4690         nodes_0_deserialized = nodes_0_deserialized_tmp;
4691         assert!(nodes_0_read.is_empty());
4692
4693         { // Channel close should result in a commitment tx
4694                 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4695                 assert_eq!(txn.len(), 1);
4696                 check_spends!(txn[0], funding_tx);
4697                 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4698         }
4699
4700         for monitor in node_0_monitors.drain(..) {
4701                 assert_eq!(nodes[0].chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor),
4702                         ChannelMonitorUpdateStatus::Completed);
4703                 check_added_monitors!(nodes[0], 1);
4704         }
4705         nodes[0].node = &nodes_0_deserialized;
4706         check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
4707
4708         // nodes[1] and nodes[2] have no lost state with nodes[0]...
4709         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4710         reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4711         //... and we can even still claim the payment!
4712         claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage);
4713
4714         nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
4715         let reestablish = get_chan_reestablish_msgs!(nodes[3], nodes[0]).pop().unwrap();
4716         nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
4717         nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4718         let mut found_err = false;
4719         for msg_event in nodes[0].node.get_and_clear_pending_msg_events() {
4720                 if let MessageSendEvent::HandleError { ref action, .. } = msg_event {
4721                         match action {
4722                                 &ErrorAction::SendErrorMessage { ref msg } => {
4723                                         assert_eq!(msg.channel_id, channel_id);
4724                                         assert!(!found_err);
4725                                         found_err = true;
4726                                 },
4727                                 _ => panic!("Unexpected event!"),
4728                         }
4729                 }
4730         }
4731         assert!(found_err);
4732 }
4733
4734 macro_rules! check_spendable_outputs {
4735         ($node: expr, $keysinterface: expr) => {
4736                 {
4737                         let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4738                         let mut txn = Vec::new();
4739                         let mut all_outputs = Vec::new();
4740                         let secp_ctx = Secp256k1::new();
4741                         for event in events.drain(..) {
4742                                 match event {
4743                                         Event::SpendableOutputs { mut outputs } => {
4744                                                 for outp in outputs.drain(..) {
4745                                                         txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4746                                                         all_outputs.push(outp);
4747                                                 }
4748                                         },
4749                                         _ => panic!("Unexpected event"),
4750                                 };
4751                         }
4752                         if all_outputs.len() > 1 {
4753                                 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) {
4754                                         txn.push(tx);
4755                                 }
4756                         }
4757                         txn
4758                 }
4759         }
4760 }
4761
4762 #[test]
4763 fn test_claim_sizeable_push_msat() {
4764         // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4765         let chanmon_cfgs = create_chanmon_cfgs(2);
4766         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4767         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4768         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4769
4770         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());
4771         nodes[1].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
4772         check_closed_broadcast!(nodes[1], true);
4773         check_added_monitors!(nodes[1], 1);
4774         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4775         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4776         assert_eq!(node_txn.len(), 1);
4777         check_spends!(node_txn[0], chan.3);
4778         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
4779
4780         mine_transaction(&nodes[1], &node_txn[0]);
4781         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4782
4783         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4784         assert_eq!(spend_txn.len(), 1);
4785         assert_eq!(spend_txn[0].input.len(), 1);
4786         check_spends!(spend_txn[0], node_txn[0]);
4787         assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4788 }
4789
4790 #[test]
4791 fn test_claim_on_remote_sizeable_push_msat() {
4792         // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4793         // to_remote output is encumbered by a P2WPKH
4794         let chanmon_cfgs = create_chanmon_cfgs(2);
4795         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4796         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4797         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4798
4799         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());
4800         nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
4801         check_closed_broadcast!(nodes[0], true);
4802         check_added_monitors!(nodes[0], 1);
4803         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4804
4805         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4806         assert_eq!(node_txn.len(), 1);
4807         check_spends!(node_txn[0], chan.3);
4808         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
4809
4810         mine_transaction(&nodes[1], &node_txn[0]);
4811         check_closed_broadcast!(nodes[1], true);
4812         check_added_monitors!(nodes[1], 1);
4813         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4814         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4815
4816         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4817         assert_eq!(spend_txn.len(), 1);
4818         check_spends!(spend_txn[0], node_txn[0]);
4819 }
4820
4821 #[test]
4822 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4823         // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4824         // to_remote output is encumbered by a P2WPKH
4825
4826         let chanmon_cfgs = create_chanmon_cfgs(2);
4827         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4828         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4829         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4830
4831         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4832         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4833         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4834         assert_eq!(revoked_local_txn[0].input.len(), 1);
4835         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4836
4837         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4838         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4839         check_closed_broadcast!(nodes[1], true);
4840         check_added_monitors!(nodes[1], 1);
4841         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4842
4843         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4844         mine_transaction(&nodes[1], &node_txn[0]);
4845         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4846
4847         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4848         assert_eq!(spend_txn.len(), 3);
4849         check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4850         check_spends!(spend_txn[1], node_txn[0]);
4851         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4852 }
4853
4854 #[test]
4855 fn test_static_spendable_outputs_preimage_tx() {
4856         let chanmon_cfgs = create_chanmon_cfgs(2);
4857         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4858         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4859         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4860
4861         // Create some initial channels
4862         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4863
4864         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
4865
4866         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4867         assert_eq!(commitment_tx[0].input.len(), 1);
4868         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4869
4870         // Settle A's commitment tx on B's chain
4871         nodes[1].node.claim_funds(payment_preimage);
4872         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
4873         check_added_monitors!(nodes[1], 1);
4874         mine_transaction(&nodes[1], &commitment_tx[0]);
4875         check_added_monitors!(nodes[1], 1);
4876         let events = nodes[1].node.get_and_clear_pending_msg_events();
4877         match events[0] {
4878                 MessageSendEvent::UpdateHTLCs { .. } => {},
4879                 _ => panic!("Unexpected event"),
4880         }
4881         match events[1] {
4882                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4883                 _ => panic!("Unexepected event"),
4884         }
4885
4886         // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4887         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4888         assert_eq!(node_txn.len(), 3);
4889         check_spends!(node_txn[0], commitment_tx[0]);
4890         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4891         check_spends!(node_txn[1], chan_1.3);
4892         check_spends!(node_txn[2], node_txn[1]);
4893
4894         mine_transaction(&nodes[1], &node_txn[0]);
4895         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4896         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4897
4898         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4899         assert_eq!(spend_txn.len(), 1);
4900         check_spends!(spend_txn[0], node_txn[0]);
4901 }
4902
4903 #[test]
4904 fn test_static_spendable_outputs_timeout_tx() {
4905         let chanmon_cfgs = create_chanmon_cfgs(2);
4906         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4907         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4908         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4909
4910         // Create some initial channels
4911         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4912
4913         // Rebalance the network a bit by relaying one payment through all the channels ...
4914         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4915
4916         let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4917
4918         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4919         assert_eq!(commitment_tx[0].input.len(), 1);
4920         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4921
4922         // Settle A's commitment tx on B' chain
4923         mine_transaction(&nodes[1], &commitment_tx[0]);
4924         check_added_monitors!(nodes[1], 1);
4925         let events = nodes[1].node.get_and_clear_pending_msg_events();
4926         match events[0] {
4927                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4928                 _ => panic!("Unexpected event"),
4929         }
4930         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4931
4932         // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4933         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4934         assert_eq!(node_txn.len(), 2); // ChannelManager : 1 local commitent tx, ChannelMonitor: timeout tx
4935         check_spends!(node_txn[0], chan_1.3.clone());
4936         check_spends!(node_txn[1],  commitment_tx[0].clone());
4937         assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4938
4939         mine_transaction(&nodes[1], &node_txn[1]);
4940         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4941         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4942         expect_payment_failed!(nodes[1], our_payment_hash, false);
4943
4944         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4945         assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4946         check_spends!(spend_txn[0], commitment_tx[0]);
4947         check_spends!(spend_txn[1], node_txn[1]);
4948         check_spends!(spend_txn[2], node_txn[1], commitment_tx[0]); // All outputs
4949 }
4950
4951 #[test]
4952 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4953         let chanmon_cfgs = create_chanmon_cfgs(2);
4954         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4955         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4956         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4957
4958         // Create some initial channels
4959         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4960
4961         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4962         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4963         assert_eq!(revoked_local_txn[0].input.len(), 1);
4964         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4965
4966         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4967
4968         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4969         check_closed_broadcast!(nodes[1], true);
4970         check_added_monitors!(nodes[1], 1);
4971         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4972
4973         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4974         assert_eq!(node_txn.len(), 2);
4975         assert_eq!(node_txn[0].input.len(), 2);
4976         check_spends!(node_txn[0], revoked_local_txn[0]);
4977
4978         mine_transaction(&nodes[1], &node_txn[0]);
4979         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4980
4981         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4982         assert_eq!(spend_txn.len(), 1);
4983         check_spends!(spend_txn[0], node_txn[0]);
4984 }
4985
4986 #[test]
4987 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4988         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4989         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4990         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4991         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4992         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4993
4994         // Create some initial channels
4995         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4996
4997         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4998         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4999         assert_eq!(revoked_local_txn[0].input.len(), 1);
5000         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5001
5002         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
5003
5004         // A will generate HTLC-Timeout from revoked commitment tx
5005         mine_transaction(&nodes[0], &revoked_local_txn[0]);
5006         check_closed_broadcast!(nodes[0], true);
5007         check_added_monitors!(nodes[0], 1);
5008         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5009         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5010
5011         let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
5012         assert_eq!(revoked_htlc_txn.len(), 2);
5013         check_spends!(revoked_htlc_txn[0], chan_1.3);
5014         assert_eq!(revoked_htlc_txn[1].input.len(), 1);
5015         assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5016         check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
5017         assert_ne!(revoked_htlc_txn[1].lock_time.0, 0); // HTLC-Timeout
5018
5019         // B will generate justice tx from A's revoked commitment/HTLC tx
5020         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
5021         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[1].clone()] });
5022         check_closed_broadcast!(nodes[1], true);
5023         check_added_monitors!(nodes[1], 1);
5024         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5025
5026         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5027         assert_eq!(node_txn.len(), 3); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs, ChannelManager: local commitment tx
5028         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5029         // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
5030         // transactions next...
5031         assert_eq!(node_txn[0].input.len(), 3);
5032         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[1]);
5033
5034         assert_eq!(node_txn[1].input.len(), 2);
5035         check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[1]);
5036         if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[1].txid() {
5037                 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
5038         } else {
5039                 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[1].txid());
5040                 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[1].input[0].previous_output);
5041         }
5042
5043         assert_eq!(node_txn[2].input.len(), 1);
5044         check_spends!(node_txn[2], chan_1.3);
5045
5046         mine_transaction(&nodes[1], &node_txn[1]);
5047         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5048
5049         // Check B's ChannelMonitor was able to generate the right spendable output descriptor
5050         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5051         assert_eq!(spend_txn.len(), 1);
5052         assert_eq!(spend_txn[0].input.len(), 1);
5053         check_spends!(spend_txn[0], node_txn[1]);
5054 }
5055
5056 #[test]
5057 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
5058         let mut chanmon_cfgs = create_chanmon_cfgs(2);
5059         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
5060         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5061         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5062         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5063
5064         // Create some initial channels
5065         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5066
5067         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5068         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5069         assert_eq!(revoked_local_txn[0].input.len(), 1);
5070         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5071
5072         // The to-be-revoked commitment tx should have one HTLC and one to_remote output
5073         assert_eq!(revoked_local_txn[0].output.len(), 2);
5074
5075         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
5076
5077         // B will generate HTLC-Success from revoked commitment tx
5078         mine_transaction(&nodes[1], &revoked_local_txn[0]);
5079         check_closed_broadcast!(nodes[1], true);
5080         check_added_monitors!(nodes[1], 1);
5081         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5082         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5083
5084         assert_eq!(revoked_htlc_txn.len(), 2);
5085         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
5086         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5087         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
5088
5089         // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
5090         let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
5091         assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
5092
5093         // A will generate justice tx from B's revoked commitment/HTLC tx
5094         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
5095         connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
5096         check_closed_broadcast!(nodes[0], true);
5097         check_added_monitors!(nodes[0], 1);
5098         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5099
5100         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5101         assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
5102
5103         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5104         // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
5105         // transactions next...
5106         assert_eq!(node_txn[0].input.len(), 2);
5107         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
5108         if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
5109                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5110         } else {
5111                 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
5112                 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5113         }
5114
5115         assert_eq!(node_txn[1].input.len(), 1);
5116         check_spends!(node_txn[1], revoked_htlc_txn[0]);
5117
5118         check_spends!(node_txn[2], chan_1.3);
5119
5120         mine_transaction(&nodes[0], &node_txn[1]);
5121         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5122
5123         // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
5124         // didn't try to generate any new transactions.
5125
5126         // Check A's ChannelMonitor was able to generate the right spendable output descriptor
5127         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5128         assert_eq!(spend_txn.len(), 3);
5129         assert_eq!(spend_txn[0].input.len(), 1);
5130         check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
5131         assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5132         check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
5133         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
5134 }
5135
5136 #[test]
5137 fn test_onchain_to_onchain_claim() {
5138         // Test that in case of channel closure, we detect the state of output and claim HTLC
5139         // on downstream peer's remote commitment tx.
5140         // First, have C claim an HTLC against its own latest commitment transaction.
5141         // Then, broadcast these to B, which should update the monitor downstream on the A<->B
5142         // channel.
5143         // Finally, check that B will claim the HTLC output if A's latest commitment transaction
5144         // gets broadcast.
5145
5146         let chanmon_cfgs = create_chanmon_cfgs(3);
5147         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5148         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5149         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5150
5151         // Create some initial channels
5152         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5153         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5154
5155         // Ensure all nodes are at the same height
5156         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5157         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5158         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5159         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5160
5161         // Rebalance the network a bit by relaying one payment through all the channels ...
5162         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5163         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5164
5165         let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
5166         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
5167         check_spends!(commitment_tx[0], chan_2.3);
5168         nodes[2].node.claim_funds(payment_preimage);
5169         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
5170         check_added_monitors!(nodes[2], 1);
5171         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5172         assert!(updates.update_add_htlcs.is_empty());
5173         assert!(updates.update_fail_htlcs.is_empty());
5174         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5175         assert!(updates.update_fail_malformed_htlcs.is_empty());
5176
5177         mine_transaction(&nodes[2], &commitment_tx[0]);
5178         check_closed_broadcast!(nodes[2], true);
5179         check_added_monitors!(nodes[2], 1);
5180         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5181
5182         let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
5183         assert_eq!(c_txn.len(), 3);
5184         assert_eq!(c_txn[0], c_txn[2]);
5185         assert_eq!(commitment_tx[0], c_txn[1]);
5186         check_spends!(c_txn[1], chan_2.3);
5187         check_spends!(c_txn[2], c_txn[1]);
5188         assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
5189         assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5190         assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5191         assert_eq!(c_txn[0].lock_time.0, 0); // Success tx
5192
5193         // 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
5194         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
5195         connect_block(&nodes[1], &Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]});
5196         check_added_monitors!(nodes[1], 1);
5197         let events = nodes[1].node.get_and_clear_pending_events();
5198         assert_eq!(events.len(), 2);
5199         match events[0] {
5200                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5201                 _ => panic!("Unexpected event"),
5202         }
5203         match events[1] {
5204                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
5205                         assert_eq!(fee_earned_msat, Some(1000));
5206                         assert_eq!(prev_channel_id, Some(chan_1.2));
5207                         assert_eq!(claim_from_onchain_tx, true);
5208                         assert_eq!(next_channel_id, Some(chan_2.2));
5209                 },
5210                 _ => panic!("Unexpected event"),
5211         }
5212         {
5213                 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5214                 // ChannelMonitor: claim tx
5215                 assert_eq!(b_txn.len(), 1);
5216                 check_spends!(b_txn[0], chan_2.3); // B local commitment tx, issued by ChannelManager
5217                 b_txn.clear();
5218         }
5219         check_added_monitors!(nodes[1], 1);
5220         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5221         assert_eq!(msg_events.len(), 3);
5222         match msg_events[0] {
5223                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5224                 _ => panic!("Unexpected event"),
5225         }
5226         match msg_events[1] {
5227                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
5228                 _ => panic!("Unexpected event"),
5229         }
5230         match msg_events[2] {
5231                 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, .. } } => {
5232                         assert!(update_add_htlcs.is_empty());
5233                         assert!(update_fail_htlcs.is_empty());
5234                         assert_eq!(update_fulfill_htlcs.len(), 1);
5235                         assert!(update_fail_malformed_htlcs.is_empty());
5236                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5237                 },
5238                 _ => panic!("Unexpected event"),
5239         };
5240         // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
5241         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5242         mine_transaction(&nodes[1], &commitment_tx[0]);
5243         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5244         let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5245         // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
5246         assert_eq!(b_txn.len(), 3);
5247         check_spends!(b_txn[1], chan_1.3);
5248         check_spends!(b_txn[2], b_txn[1]);
5249         check_spends!(b_txn[0], commitment_tx[0]);
5250         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5251         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5252         assert_eq!(b_txn[0].lock_time.0, 0); // Success tx
5253
5254         check_closed_broadcast!(nodes[1], true);
5255         check_added_monitors!(nodes[1], 1);
5256 }
5257
5258 #[test]
5259 fn test_duplicate_payment_hash_one_failure_one_success() {
5260         // Topology : A --> B --> C --> D
5261         // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5262         // Note that because C will refuse to generate two payment secrets for the same payment hash,
5263         // we forward one of the payments onwards to D.
5264         let chanmon_cfgs = create_chanmon_cfgs(4);
5265         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
5266         // When this test was written, the default base fee floated based on the HTLC count.
5267         // It is now fixed, so we simply set the fee to the expected value here.
5268         let mut config = test_default_channel_config();
5269         config.channel_config.forwarding_fee_base_msat = 196;
5270         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
5271                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5272         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
5273
5274         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5275         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5276         create_announced_chan_between_nodes(&nodes, 2, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5277
5278         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5279         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5280         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5281         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5282         connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
5283
5284         let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 900_000);
5285
5286         let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200).unwrap();
5287         // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
5288         // script push size limit so that the below script length checks match
5289         // ACCEPTED_HTLC_SCRIPT_WEIGHT.
5290         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id())
5291                 .with_features(channelmanager::provided_invoice_features());
5292         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 900000, TEST_FINAL_CLTV - 40);
5293         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 900000, duplicate_payment_hash, payment_secret);
5294
5295         let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5296         assert_eq!(commitment_txn[0].input.len(), 1);
5297         check_spends!(commitment_txn[0], chan_2.3);
5298
5299         mine_transaction(&nodes[1], &commitment_txn[0]);
5300         check_closed_broadcast!(nodes[1], true);
5301         check_added_monitors!(nodes[1], 1);
5302         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5303         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
5304
5305         let htlc_timeout_tx;
5306         { // Extract one of the two HTLC-Timeout transaction
5307                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5308                 // ChannelMonitor: timeout tx * 2-or-3, ChannelManager: local commitment tx
5309                 assert!(node_txn.len() == 4 || node_txn.len() == 3);
5310                 check_spends!(node_txn[0], chan_2.3);
5311
5312                 check_spends!(node_txn[1], commitment_txn[0]);
5313                 assert_eq!(node_txn[1].input.len(), 1);
5314
5315                 if node_txn.len() > 3 {
5316                         check_spends!(node_txn[2], commitment_txn[0]);
5317                         assert_eq!(node_txn[2].input.len(), 1);
5318                         assert_eq!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
5319
5320                         check_spends!(node_txn[3], commitment_txn[0]);
5321                         assert_ne!(node_txn[1].input[0].previous_output, node_txn[3].input[0].previous_output);
5322                 } else {
5323                         check_spends!(node_txn[2], commitment_txn[0]);
5324                         assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
5325                 }
5326
5327                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5328                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5329                 if node_txn.len() > 3 {
5330                         assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5331                 }
5332                 htlc_timeout_tx = node_txn[1].clone();
5333         }
5334
5335         nodes[2].node.claim_funds(our_payment_preimage);
5336         expect_payment_claimed!(nodes[2], duplicate_payment_hash, 900_000);
5337
5338         mine_transaction(&nodes[2], &commitment_txn[0]);
5339         check_added_monitors!(nodes[2], 2);
5340         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5341         let events = nodes[2].node.get_and_clear_pending_msg_events();
5342         match events[0] {
5343                 MessageSendEvent::UpdateHTLCs { .. } => {},
5344                 _ => panic!("Unexpected event"),
5345         }
5346         match events[1] {
5347                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5348                 _ => panic!("Unexepected event"),
5349         }
5350         let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5351         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)
5352         check_spends!(htlc_success_txn[0], commitment_txn[0]);
5353         check_spends!(htlc_success_txn[1], commitment_txn[0]);
5354         assert_eq!(htlc_success_txn[0].input.len(), 1);
5355         assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5356         assert_eq!(htlc_success_txn[1].input.len(), 1);
5357         assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5358         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
5359         assert_eq!(htlc_success_txn[2], commitment_txn[0]);
5360         assert_eq!(htlc_success_txn[3], htlc_success_txn[0]);
5361         assert_eq!(htlc_success_txn[4], htlc_success_txn[1]);
5362         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
5363
5364         mine_transaction(&nodes[1], &htlc_timeout_tx);
5365         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5366         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 }]);
5367         let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5368         assert!(htlc_updates.update_add_htlcs.is_empty());
5369         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5370         let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
5371         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5372         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5373         check_added_monitors!(nodes[1], 1);
5374
5375         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5376         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5377         {
5378                 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5379         }
5380         expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
5381
5382         // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5383         // Note that the fee paid is effectively double as the HTLC value (including the nodes[1] fee
5384         // and nodes[2] fee) is rounded down and then claimed in full.
5385         mine_transaction(&nodes[1], &htlc_success_txn[0]);
5386         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196*2), true, true);
5387         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5388         assert!(updates.update_add_htlcs.is_empty());
5389         assert!(updates.update_fail_htlcs.is_empty());
5390         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5391         assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
5392         assert!(updates.update_fail_malformed_htlcs.is_empty());
5393         check_added_monitors!(nodes[1], 1);
5394
5395         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5396         commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5397
5398         let events = nodes[0].node.get_and_clear_pending_events();
5399         match events[0] {
5400                 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
5401                         assert_eq!(*payment_preimage, our_payment_preimage);
5402                         assert_eq!(*payment_hash, duplicate_payment_hash);
5403                 }
5404                 _ => panic!("Unexpected event"),
5405         }
5406 }
5407
5408 #[test]
5409 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5410         let chanmon_cfgs = create_chanmon_cfgs(2);
5411         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5412         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5413         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5414
5415         // Create some initial channels
5416         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5417
5418         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
5419         let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5420         assert_eq!(local_txn.len(), 1);
5421         assert_eq!(local_txn[0].input.len(), 1);
5422         check_spends!(local_txn[0], chan_1.3);
5423
5424         // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5425         nodes[1].node.claim_funds(payment_preimage);
5426         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
5427         check_added_monitors!(nodes[1], 1);
5428
5429         mine_transaction(&nodes[1], &local_txn[0]);
5430         check_added_monitors!(nodes[1], 1);
5431         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5432         let events = nodes[1].node.get_and_clear_pending_msg_events();
5433         match events[0] {
5434                 MessageSendEvent::UpdateHTLCs { .. } => {},
5435                 _ => panic!("Unexpected event"),
5436         }
5437         match events[1] {
5438                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5439                 _ => panic!("Unexepected event"),
5440         }
5441         let node_tx = {
5442                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5443                 assert_eq!(node_txn.len(), 3);
5444                 assert_eq!(node_txn[0], node_txn[2]);
5445                 assert_eq!(node_txn[1], local_txn[0]);
5446                 assert_eq!(node_txn[0].input.len(), 1);
5447                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5448                 check_spends!(node_txn[0], local_txn[0]);
5449                 node_txn[0].clone()
5450         };
5451
5452         mine_transaction(&nodes[1], &node_tx);
5453         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
5454
5455         // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5456         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5457         assert_eq!(spend_txn.len(), 1);
5458         assert_eq!(spend_txn[0].input.len(), 1);
5459         check_spends!(spend_txn[0], node_tx);
5460         assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5461 }
5462
5463 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5464         // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5465         // unrevoked commitment transaction.
5466         // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5467         // a remote RAA before they could be failed backwards (and combinations thereof).
5468         // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5469         // use the same payment hashes.
5470         // Thus, we use a six-node network:
5471         //
5472         // A \         / E
5473         //    - C - D -
5474         // B /         \ F
5475         // And test where C fails back to A/B when D announces its latest commitment transaction
5476         let chanmon_cfgs = create_chanmon_cfgs(6);
5477         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5478         // When this test was written, the default base fee floated based on the HTLC count.
5479         // It is now fixed, so we simply set the fee to the expected value here.
5480         let mut config = test_default_channel_config();
5481         config.channel_config.forwarding_fee_base_msat = 196;
5482         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
5483                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5484         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5485
5486         let _chan_0_2 = create_announced_chan_between_nodes(&nodes, 0, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5487         let _chan_1_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5488         let chan_2_3 = create_announced_chan_between_nodes(&nodes, 2, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5489         let chan_3_4 = create_announced_chan_between_nodes(&nodes, 3, 4, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5490         let chan_3_5  = create_announced_chan_between_nodes(&nodes, 3, 5, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5491
5492         // Rebalance and check output sanity...
5493         send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
5494         send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
5495         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 2);
5496
5497         let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan_2_3.2).unwrap().holder_dust_limit_satoshis;
5498         // 0th HTLC:
5499         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
5500         // 1st HTLC:
5501         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
5502         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5503         // 2nd HTLC:
5504         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
5505         // 3rd HTLC:
5506         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
5507         // 4th HTLC:
5508         let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5509         // 5th HTLC:
5510         let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5511         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5512         // 6th HTLC:
5513         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());
5514         // 7th HTLC:
5515         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());
5516
5517         // 8th HTLC:
5518         let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5519         // 9th HTLC:
5520         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5521         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
5522
5523         // 10th HTLC:
5524         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
5525         // 11th HTLC:
5526         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5527         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());
5528
5529         // Double-check that six of the new HTLC were added
5530         // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5531         // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5532         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2).len(), 1);
5533         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 8);
5534
5535         // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5536         // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5537         nodes[4].node.fail_htlc_backwards(&payment_hash_1);
5538         nodes[4].node.fail_htlc_backwards(&payment_hash_3);
5539         nodes[4].node.fail_htlc_backwards(&payment_hash_5);
5540         nodes[4].node.fail_htlc_backwards(&payment_hash_6);
5541         check_added_monitors!(nodes[4], 0);
5542
5543         let failed_destinations = vec![
5544                 HTLCDestination::FailedPayment { payment_hash: payment_hash_1 },
5545                 HTLCDestination::FailedPayment { payment_hash: payment_hash_3 },
5546                 HTLCDestination::FailedPayment { payment_hash: payment_hash_5 },
5547                 HTLCDestination::FailedPayment { payment_hash: payment_hash_6 },
5548         ];
5549         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[4], failed_destinations);
5550         check_added_monitors!(nodes[4], 1);
5551
5552         let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5553         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5554         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5555         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5556         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5557         commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5558
5559         // Fail 3rd below-dust and 7th above-dust HTLCs
5560         nodes[5].node.fail_htlc_backwards(&payment_hash_2);
5561         nodes[5].node.fail_htlc_backwards(&payment_hash_4);
5562         check_added_monitors!(nodes[5], 0);
5563
5564         let failed_destinations_2 = vec![
5565                 HTLCDestination::FailedPayment { payment_hash: payment_hash_2 },
5566                 HTLCDestination::FailedPayment { payment_hash: payment_hash_4 },
5567         ];
5568         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[5], failed_destinations_2);
5569         check_added_monitors!(nodes[5], 1);
5570
5571         let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5572         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5573         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5574         commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5575
5576         let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5577
5578         // After 4 and 2 removes respectively above in nodes[4] and nodes[5], nodes[3] should receive 6 PaymentForwardedFailed events
5579         let failed_destinations_3 = vec![
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[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5582                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5583                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5584                 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5585                 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5586         ];
5587         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations_3);
5588         check_added_monitors!(nodes[3], 1);
5589         let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5590         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5591         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5592         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5593         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5594         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5595         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5596         if deliver_last_raa {
5597                 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5598         } else {
5599                 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5600         }
5601
5602         // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5603         // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5604         // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5605         // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5606         //
5607         // We now broadcast the latest commitment transaction, which *should* result in failures for
5608         // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5609         // the non-broadcast above-dust HTLCs.
5610         //
5611         // Alternatively, we may broadcast the previous commitment transaction, which should only
5612         // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5613         let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5614
5615         if announce_latest {
5616                 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5617         } else {
5618                 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5619         }
5620         let events = nodes[2].node.get_and_clear_pending_events();
5621         let close_event = if deliver_last_raa {
5622                 assert_eq!(events.len(), 2 + 6);
5623                 events.last().clone().unwrap()
5624         } else {
5625                 assert_eq!(events.len(), 1);
5626                 events.last().clone().unwrap()
5627         };
5628         match close_event {
5629                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5630                 _ => panic!("Unexpected event"),
5631         }
5632
5633         connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5634         check_closed_broadcast!(nodes[2], true);
5635         if deliver_last_raa {
5636                 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5637
5638                 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();
5639                 expect_htlc_handling_failed_destinations!(nodes[2].node.get_and_clear_pending_events(), expected_destinations);
5640         } else {
5641                 let expected_destinations: Vec<HTLCDestination> = if announce_latest {
5642                         repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(9).collect()
5643                 } else {
5644                         repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(6).collect()
5645                 };
5646
5647                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], expected_destinations);
5648         }
5649         check_added_monitors!(nodes[2], 3);
5650
5651         let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5652         assert_eq!(cs_msgs.len(), 2);
5653         let mut a_done = false;
5654         for msg in cs_msgs {
5655                 match msg {
5656                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5657                                 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5658                                 // should be failed-backwards here.
5659                                 let target = if *node_id == nodes[0].node.get_our_node_id() {
5660                                         // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5661                                         for htlc in &updates.update_fail_htlcs {
5662                                                 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 });
5663                                         }
5664                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5665                                         assert!(!a_done);
5666                                         a_done = true;
5667                                         &nodes[0]
5668                                 } else {
5669                                         // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5670                                         for htlc in &updates.update_fail_htlcs {
5671                                                 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5672                                         }
5673                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5674                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5675                                         &nodes[1]
5676                                 };
5677                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5678                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5679                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5680                                 if announce_latest {
5681                                         target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5682                                         if *node_id == nodes[0].node.get_our_node_id() {
5683                                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5684                                         }
5685                                 }
5686                                 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5687                         },
5688                         _ => panic!("Unexpected event"),
5689                 }
5690         }
5691
5692         let as_events = nodes[0].node.get_and_clear_pending_events();
5693         assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5694         let mut as_failds = HashSet::new();
5695         let mut as_updates = 0;
5696         for event in as_events.iter() {
5697                 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref network_update, .. } = event {
5698                         assert!(as_failds.insert(*payment_hash));
5699                         if *payment_hash != payment_hash_2 {
5700                                 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5701                         } else {
5702                                 assert!(!payment_failed_permanently);
5703                         }
5704                         if network_update.is_some() {
5705                                 as_updates += 1;
5706                         }
5707                 } else { panic!("Unexpected event"); }
5708         }
5709         assert!(as_failds.contains(&payment_hash_1));
5710         assert!(as_failds.contains(&payment_hash_2));
5711         if announce_latest {
5712                 assert!(as_failds.contains(&payment_hash_3));
5713                 assert!(as_failds.contains(&payment_hash_5));
5714         }
5715         assert!(as_failds.contains(&payment_hash_6));
5716
5717         let bs_events = nodes[1].node.get_and_clear_pending_events();
5718         assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5719         let mut bs_failds = HashSet::new();
5720         let mut bs_updates = 0;
5721         for event in bs_events.iter() {
5722                 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref network_update, .. } = event {
5723                         assert!(bs_failds.insert(*payment_hash));
5724                         if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5725                                 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5726                         } else {
5727                                 assert!(!payment_failed_permanently);
5728                         }
5729                         if network_update.is_some() {
5730                                 bs_updates += 1;
5731                         }
5732                 } else { panic!("Unexpected event"); }
5733         }
5734         assert!(bs_failds.contains(&payment_hash_1));
5735         assert!(bs_failds.contains(&payment_hash_2));
5736         if announce_latest {
5737                 assert!(bs_failds.contains(&payment_hash_4));
5738         }
5739         assert!(bs_failds.contains(&payment_hash_5));
5740
5741         // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5742         // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5743         // unknown-preimage-etc, B should have gotten 2. Thus, in the
5744         // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5745         assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5746         assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5747 }
5748
5749 #[test]
5750 fn test_fail_backwards_latest_remote_announce_a() {
5751         do_test_fail_backwards_unrevoked_remote_announce(false, true);
5752 }
5753
5754 #[test]
5755 fn test_fail_backwards_latest_remote_announce_b() {
5756         do_test_fail_backwards_unrevoked_remote_announce(true, true);
5757 }
5758
5759 #[test]
5760 fn test_fail_backwards_previous_remote_announce() {
5761         do_test_fail_backwards_unrevoked_remote_announce(false, false);
5762         // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5763         // tested for in test_commitment_revoked_fail_backward_exhaustive()
5764 }
5765
5766 #[test]
5767 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5768         let chanmon_cfgs = create_chanmon_cfgs(2);
5769         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5770         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5771         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5772
5773         // Create some initial channels
5774         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5775
5776         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5777         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5778         assert_eq!(local_txn[0].input.len(), 1);
5779         check_spends!(local_txn[0], chan_1.3);
5780
5781         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5782         mine_transaction(&nodes[0], &local_txn[0]);
5783         check_closed_broadcast!(nodes[0], true);
5784         check_added_monitors!(nodes[0], 1);
5785         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5786         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5787
5788         let htlc_timeout = {
5789                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5790                 assert_eq!(node_txn.len(), 2);
5791                 check_spends!(node_txn[0], chan_1.3);
5792                 assert_eq!(node_txn[1].input.len(), 1);
5793                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5794                 check_spends!(node_txn[1], local_txn[0]);
5795                 node_txn[1].clone()
5796         };
5797
5798         mine_transaction(&nodes[0], &htlc_timeout);
5799         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5800         expect_payment_failed!(nodes[0], our_payment_hash, false);
5801
5802         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5803         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5804         assert_eq!(spend_txn.len(), 3);
5805         check_spends!(spend_txn[0], local_txn[0]);
5806         assert_eq!(spend_txn[1].input.len(), 1);
5807         check_spends!(spend_txn[1], htlc_timeout);
5808         assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5809         assert_eq!(spend_txn[2].input.len(), 2);
5810         check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5811         assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5812                 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5813 }
5814
5815 #[test]
5816 fn test_key_derivation_params() {
5817         // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5818         // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5819         // let us re-derive the channel key set to then derive a delayed_payment_key.
5820
5821         let chanmon_cfgs = create_chanmon_cfgs(3);
5822
5823         // We manually create the node configuration to backup the seed.
5824         let seed = [42; 32];
5825         let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5826         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);
5827         let network_graph = NetworkGraph::new(chanmon_cfgs[0].chain_source.genesis_hash, &chanmon_cfgs[0].logger);
5828         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() };
5829         let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5830         node_cfgs.remove(0);
5831         node_cfgs.insert(0, node);
5832
5833         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5834         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5835
5836         // Create some initial channels
5837         // Create a dummy channel to advance index by one and thus test re-derivation correctness
5838         // for node 0
5839         let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5840         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5841         assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5842
5843         // Ensure all nodes are at the same height
5844         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5845         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5846         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5847         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5848
5849         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5850         let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5851         let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5852         assert_eq!(local_txn_1[0].input.len(), 1);
5853         check_spends!(local_txn_1[0], chan_1.3);
5854
5855         // We check funding pubkey are unique
5856         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]));
5857         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]));
5858         if from_0_funding_key_0 == from_1_funding_key_0
5859             || from_0_funding_key_0 == from_1_funding_key_1
5860             || from_0_funding_key_1 == from_1_funding_key_0
5861             || from_0_funding_key_1 == from_1_funding_key_1 {
5862                 panic!("Funding pubkeys aren't unique");
5863         }
5864
5865         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5866         mine_transaction(&nodes[0], &local_txn_1[0]);
5867         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5868         check_closed_broadcast!(nodes[0], true);
5869         check_added_monitors!(nodes[0], 1);
5870         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5871
5872         let htlc_timeout = {
5873                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5874                 assert_eq!(node_txn[1].input.len(), 1);
5875                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5876                 check_spends!(node_txn[1], local_txn_1[0]);
5877                 node_txn[1].clone()
5878         };
5879
5880         mine_transaction(&nodes[0], &htlc_timeout);
5881         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5882         expect_payment_failed!(nodes[0], our_payment_hash, false);
5883
5884         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5885         let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5886         let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5887         assert_eq!(spend_txn.len(), 3);
5888         check_spends!(spend_txn[0], local_txn_1[0]);
5889         assert_eq!(spend_txn[1].input.len(), 1);
5890         check_spends!(spend_txn[1], htlc_timeout);
5891         assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5892         assert_eq!(spend_txn[2].input.len(), 2);
5893         check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5894         assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5895                 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5896 }
5897
5898 #[test]
5899 fn test_static_output_closing_tx() {
5900         let chanmon_cfgs = create_chanmon_cfgs(2);
5901         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5902         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5903         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5904
5905         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5906
5907         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5908         let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5909
5910         mine_transaction(&nodes[0], &closing_tx);
5911         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5912         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5913
5914         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5915         assert_eq!(spend_txn.len(), 1);
5916         check_spends!(spend_txn[0], closing_tx);
5917
5918         mine_transaction(&nodes[1], &closing_tx);
5919         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5920         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5921
5922         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5923         assert_eq!(spend_txn.len(), 1);
5924         check_spends!(spend_txn[0], closing_tx);
5925 }
5926
5927 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5928         let chanmon_cfgs = create_chanmon_cfgs(2);
5929         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5930         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5931         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5932         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5933
5934         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3_000_000 });
5935
5936         // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5937         // present in B's local commitment transaction, but none of A's commitment transactions.
5938         nodes[1].node.claim_funds(payment_preimage);
5939         check_added_monitors!(nodes[1], 1);
5940         expect_payment_claimed!(nodes[1], payment_hash, if use_dust { 50000 } else { 3_000_000 });
5941
5942         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5943         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5944         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
5945
5946         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5947         check_added_monitors!(nodes[0], 1);
5948         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5949         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5950         check_added_monitors!(nodes[1], 1);
5951
5952         let starting_block = nodes[1].best_block_info();
5953         let mut block = Block {
5954                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
5955                 txdata: vec![],
5956         };
5957         for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5958                 connect_block(&nodes[1], &block);
5959                 block.header.prev_blockhash = block.block_hash();
5960         }
5961         test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5962         check_closed_broadcast!(nodes[1], true);
5963         check_added_monitors!(nodes[1], 1);
5964         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5965 }
5966
5967 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5968         let chanmon_cfgs = create_chanmon_cfgs(2);
5969         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5970         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5971         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5972         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5973
5974         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5975         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
5976         check_added_monitors!(nodes[0], 1);
5977
5978         let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5979
5980         // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5981         // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5982         // to "time out" the HTLC.
5983
5984         let starting_block = nodes[1].best_block_info();
5985         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
5986
5987         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5988                 connect_block(&nodes[0], &Block { header, txdata: Vec::new()});
5989                 header.prev_blockhash = header.block_hash();
5990         }
5991         test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5992         check_closed_broadcast!(nodes[0], true);
5993         check_added_monitors!(nodes[0], 1);
5994         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5995 }
5996
5997 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5998         let chanmon_cfgs = create_chanmon_cfgs(3);
5999         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6000         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6001         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6002         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6003
6004         // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
6005         // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
6006         // Also optionally test that we *don't* fail the channel in case the commitment transaction was
6007         // actually revoked.
6008         let htlc_value = if use_dust { 50000 } else { 3000000 };
6009         let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
6010         nodes[1].node.fail_htlc_backwards(&our_payment_hash);
6011         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
6012         check_added_monitors!(nodes[1], 1);
6013
6014         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6015         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
6016         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
6017         check_added_monitors!(nodes[0], 1);
6018         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6019         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
6020         check_added_monitors!(nodes[1], 1);
6021         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
6022         check_added_monitors!(nodes[1], 1);
6023         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
6024
6025         if check_revoke_no_close {
6026                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
6027                 check_added_monitors!(nodes[0], 1);
6028         }
6029
6030         let starting_block = nodes[1].best_block_info();
6031         let mut block = Block {
6032                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
6033                 txdata: vec![],
6034         };
6035         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
6036                 connect_block(&nodes[0], &block);
6037                 block.header.prev_blockhash = block.block_hash();
6038         }
6039         if !check_revoke_no_close {
6040                 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
6041                 check_closed_broadcast!(nodes[0], true);
6042                 check_added_monitors!(nodes[0], 1);
6043                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6044         } else {
6045                 expect_payment_failed!(nodes[0], our_payment_hash, true);
6046         }
6047 }
6048
6049 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
6050 // There are only a few cases to test here:
6051 //  * its not really normative behavior, but we test that below-dust HTLCs "included" in
6052 //    broadcastable commitment transactions result in channel closure,
6053 //  * its included in an unrevoked-but-previous remote commitment transaction,
6054 //  * its included in the latest remote or local commitment transactions.
6055 // We test each of the three possible commitment transactions individually and use both dust and
6056 // non-dust HTLCs.
6057 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
6058 // assume they are handled the same across all six cases, as both outbound and inbound failures are
6059 // tested for at least one of the cases in other tests.
6060 #[test]
6061 fn htlc_claim_single_commitment_only_a() {
6062         do_htlc_claim_local_commitment_only(true);
6063         do_htlc_claim_local_commitment_only(false);
6064
6065         do_htlc_claim_current_remote_commitment_only(true);
6066         do_htlc_claim_current_remote_commitment_only(false);
6067 }
6068
6069 #[test]
6070 fn htlc_claim_single_commitment_only_b() {
6071         do_htlc_claim_previous_remote_commitment_only(true, false);
6072         do_htlc_claim_previous_remote_commitment_only(false, false);
6073         do_htlc_claim_previous_remote_commitment_only(true, true);
6074         do_htlc_claim_previous_remote_commitment_only(false, true);
6075 }
6076
6077 #[test]
6078 #[should_panic]
6079 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
6080         let chanmon_cfgs = create_chanmon_cfgs(2);
6081         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6082         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6083         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6084         // Force duplicate randomness for every get-random call
6085         for node in nodes.iter() {
6086                 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
6087         }
6088
6089         // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
6090         let channel_value_satoshis=10000;
6091         let push_msat=10001;
6092         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
6093         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6094         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &node0_to_1_send_open_channel);
6095         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
6096
6097         // Create a second channel with the same random values. This used to panic due to a colliding
6098         // channel_id, but now panics due to a colliding outbound SCID alias.
6099         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6100 }
6101
6102 #[test]
6103 fn bolt2_open_channel_sending_node_checks_part2() {
6104         let chanmon_cfgs = create_chanmon_cfgs(2);
6105         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6106         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6107         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6108
6109         // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
6110         let channel_value_satoshis=2^24;
6111         let push_msat=10001;
6112         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6113
6114         // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
6115         let channel_value_satoshis=10000;
6116         // Test when push_msat is equal to 1000 * funding_satoshis.
6117         let push_msat=1000*channel_value_satoshis+1;
6118         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6119
6120         // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
6121         let channel_value_satoshis=10000;
6122         let push_msat=10001;
6123         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
6124         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6125         assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
6126
6127         // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
6128         // 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
6129         assert!(node0_to_1_send_open_channel.channel_flags<=1);
6130
6131         // 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.
6132         assert!(BREAKDOWN_TIMEOUT>0);
6133         assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
6134
6135         // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
6136         let chain_hash=genesis_block(Network::Testnet).header.block_hash();
6137         assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
6138
6139         // 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.
6140         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
6141         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
6142         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
6143         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
6144         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
6145 }
6146
6147 #[test]
6148 fn bolt2_open_channel_sane_dust_limit() {
6149         let chanmon_cfgs = create_chanmon_cfgs(2);
6150         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6151         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6152         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6153
6154         let channel_value_satoshis=1000000;
6155         let push_msat=10001;
6156         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
6157         let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6158         node0_to_1_send_open_channel.dust_limit_satoshis = 547;
6159         node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
6160
6161         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &node0_to_1_send_open_channel);
6162         let events = nodes[1].node.get_and_clear_pending_msg_events();
6163         let err_msg = match events[0] {
6164                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
6165                         msg.clone()
6166                 },
6167                 _ => panic!("Unexpected event"),
6168         };
6169         assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
6170 }
6171
6172 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
6173 // originated from our node, its failure is surfaced to the user. We trigger this failure to
6174 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
6175 // is no longer affordable once it's freed.
6176 #[test]
6177 fn test_fail_holding_cell_htlc_upon_free() {
6178         let chanmon_cfgs = create_chanmon_cfgs(2);
6179         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6180         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6181         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6182         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6183
6184         // First nodes[0] generates an update_fee, setting the channel's
6185         // pending_update_fee.
6186         {
6187                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6188                 *feerate_lock += 20;
6189         }
6190         nodes[0].node.timer_tick_occurred();
6191         check_added_monitors!(nodes[0], 1);
6192
6193         let events = nodes[0].node.get_and_clear_pending_msg_events();
6194         assert_eq!(events.len(), 1);
6195         let (update_msg, commitment_signed) = match events[0] {
6196                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6197                         (update_fee.as_ref(), commitment_signed)
6198                 },
6199                 _ => panic!("Unexpected event"),
6200         };
6201
6202         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6203
6204         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6205         let channel_reserve = chan_stat.channel_reserve_msat;
6206         let feerate = get_feerate!(nodes[0], chan.2);
6207         let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6208
6209         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6210         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6211         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6212
6213         // Send a payment which passes reserve checks but gets stuck in the holding cell.
6214         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6215         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6216         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6217
6218         // Flush the pending fee update.
6219         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6220         let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6221         check_added_monitors!(nodes[1], 1);
6222         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
6223         check_added_monitors!(nodes[0], 1);
6224
6225         // Upon receipt of the RAA, there will be an attempt to resend the holding cell
6226         // HTLC, but now that the fee has been raised the payment will now fail, causing
6227         // us to surface its failure to the user.
6228         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6229         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6230         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);
6231         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 {}",
6232                 hex::encode(our_payment_hash.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6233         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6234
6235         // Check that the payment failed to be sent out.
6236         let events = nodes[0].node.get_and_clear_pending_events();
6237         assert_eq!(events.len(), 1);
6238         match &events[0] {
6239                 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, ref network_update, ref all_paths_failed, ref short_channel_id, .. } => {
6240                         assert_eq!(PaymentId(our_payment_hash.0), *payment_id.as_ref().unwrap());
6241                         assert_eq!(our_payment_hash.clone(), *payment_hash);
6242                         assert_eq!(*payment_failed_permanently, false);
6243                         assert_eq!(*all_paths_failed, true);
6244                         assert_eq!(*network_update, None);
6245                         assert_eq!(*short_channel_id, Some(route.paths[0][0].short_channel_id));
6246                 },
6247                 _ => panic!("Unexpected event"),
6248         }
6249 }
6250
6251 // Test that if multiple HTLCs are released from the holding cell and one is
6252 // valid but the other is no longer valid upon release, the valid HTLC can be
6253 // successfully completed while the other one fails as expected.
6254 #[test]
6255 fn test_free_and_fail_holding_cell_htlcs() {
6256         let chanmon_cfgs = create_chanmon_cfgs(2);
6257         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6258         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6259         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6260         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6261
6262         // First nodes[0] generates an update_fee, setting the channel's
6263         // pending_update_fee.
6264         {
6265                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6266                 *feerate_lock += 200;
6267         }
6268         nodes[0].node.timer_tick_occurred();
6269         check_added_monitors!(nodes[0], 1);
6270
6271         let events = nodes[0].node.get_and_clear_pending_msg_events();
6272         assert_eq!(events.len(), 1);
6273         let (update_msg, commitment_signed) = match events[0] {
6274                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6275                         (update_fee.as_ref(), commitment_signed)
6276                 },
6277                 _ => panic!("Unexpected event"),
6278         };
6279
6280         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6281
6282         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6283         let channel_reserve = chan_stat.channel_reserve_msat;
6284         let feerate = get_feerate!(nodes[0], chan.2);
6285         let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6286
6287         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6288         let amt_1 = 20000;
6289         let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors) - amt_1;
6290         let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
6291         let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
6292
6293         // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6294         nodes[0].node.send_payment(&route_1, payment_hash_1, &Some(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
6295         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6296         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6297         let payment_id_2 = PaymentId(nodes[0].keys_manager.get_secure_random_bytes());
6298         nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2), payment_id_2).unwrap();
6299         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6300         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6301
6302         // Flush the pending fee update.
6303         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6304         let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6305         check_added_monitors!(nodes[1], 1);
6306         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6307         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6308         check_added_monitors!(nodes[0], 2);
6309
6310         // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6311         // but now that the fee has been raised the second payment will now fail, causing us
6312         // to surface its failure to the user. The first payment should succeed.
6313         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6314         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6315         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);
6316         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 {}",
6317                 hex::encode(payment_hash_2.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6318         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6319
6320         // Check that the second payment failed to be sent out.
6321         let events = nodes[0].node.get_and_clear_pending_events();
6322         assert_eq!(events.len(), 1);
6323         match &events[0] {
6324                 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, ref network_update, ref all_paths_failed, ref short_channel_id, .. } => {
6325                         assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
6326                         assert_eq!(payment_hash_2.clone(), *payment_hash);
6327                         assert_eq!(*payment_failed_permanently, false);
6328                         assert_eq!(*all_paths_failed, true);
6329                         assert_eq!(*network_update, None);
6330                         assert_eq!(*short_channel_id, Some(route_2.paths[0][0].short_channel_id));
6331                 },
6332                 _ => panic!("Unexpected event"),
6333         }
6334
6335         // Complete the first payment and the RAA from the fee update.
6336         let (payment_event, send_raa_event) = {
6337                 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6338                 assert_eq!(msgs.len(), 2);
6339                 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6340         };
6341         let raa = match send_raa_event {
6342                 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6343                 _ => panic!("Unexpected event"),
6344         };
6345         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6346         check_added_monitors!(nodes[1], 1);
6347         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6348         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6349         let events = nodes[1].node.get_and_clear_pending_events();
6350         assert_eq!(events.len(), 1);
6351         match events[0] {
6352                 Event::PendingHTLCsForwardable { .. } => {},
6353                 _ => panic!("Unexpected event"),
6354         }
6355         nodes[1].node.process_pending_htlc_forwards();
6356         let events = nodes[1].node.get_and_clear_pending_events();
6357         assert_eq!(events.len(), 1);
6358         match events[0] {
6359                 Event::PaymentReceived { .. } => {},
6360                 _ => panic!("Unexpected event"),
6361         }
6362         nodes[1].node.claim_funds(payment_preimage_1);
6363         check_added_monitors!(nodes[1], 1);
6364         expect_payment_claimed!(nodes[1], payment_hash_1, amt_1);
6365
6366         let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6367         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6368         commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6369         expect_payment_sent!(nodes[0], payment_preimage_1);
6370 }
6371
6372 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6373 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6374 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6375 // once it's freed.
6376 #[test]
6377 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6378         let chanmon_cfgs = create_chanmon_cfgs(3);
6379         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6380         // When this test was written, the default base fee floated based on the HTLC count.
6381         // It is now fixed, so we simply set the fee to the expected value here.
6382         let mut config = test_default_channel_config();
6383         config.channel_config.forwarding_fee_base_msat = 196;
6384         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
6385         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6386         let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6387         let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6388
6389         // First nodes[1] generates an update_fee, setting the channel's
6390         // pending_update_fee.
6391         {
6392                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
6393                 *feerate_lock += 20;
6394         }
6395         nodes[1].node.timer_tick_occurred();
6396         check_added_monitors!(nodes[1], 1);
6397
6398         let events = nodes[1].node.get_and_clear_pending_msg_events();
6399         assert_eq!(events.len(), 1);
6400         let (update_msg, commitment_signed) = match events[0] {
6401                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6402                         (update_fee.as_ref(), commitment_signed)
6403                 },
6404                 _ => panic!("Unexpected event"),
6405         };
6406
6407         nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6408
6409         let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
6410         let channel_reserve = chan_stat.channel_reserve_msat;
6411         let feerate = get_feerate!(nodes[0], chan_0_1.2);
6412         let opt_anchors = get_opt_anchors!(nodes[0], chan_0_1.2);
6413
6414         // Send a payment which passes reserve checks but gets stuck in the holding cell.
6415         let feemsat = 239;
6416         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
6417         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors) - total_routing_fee_msat;
6418         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
6419         let payment_event = {
6420                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6421                 check_added_monitors!(nodes[0], 1);
6422
6423                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6424                 assert_eq!(events.len(), 1);
6425
6426                 SendEvent::from_event(events.remove(0))
6427         };
6428         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6429         check_added_monitors!(nodes[1], 0);
6430         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6431         expect_pending_htlcs_forwardable!(nodes[1]);
6432
6433         chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
6434         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6435
6436         // Flush the pending fee update.
6437         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6438         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6439         check_added_monitors!(nodes[2], 1);
6440         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6441         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6442         check_added_monitors!(nodes[1], 2);
6443
6444         // A final RAA message is generated to finalize the fee update.
6445         let events = nodes[1].node.get_and_clear_pending_msg_events();
6446         assert_eq!(events.len(), 1);
6447
6448         let raa_msg = match &events[0] {
6449                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6450                         msg.clone()
6451                 },
6452                 _ => panic!("Unexpected event"),
6453         };
6454
6455         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6456         check_added_monitors!(nodes[2], 1);
6457         assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6458
6459         // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6460         let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6461         assert_eq!(process_htlc_forwards_event.len(), 2);
6462         match &process_htlc_forwards_event[0] {
6463                 &Event::PendingHTLCsForwardable { .. } => {},
6464                 _ => panic!("Unexpected event"),
6465         }
6466
6467         // In response, we call ChannelManager's process_pending_htlc_forwards
6468         nodes[1].node.process_pending_htlc_forwards();
6469         check_added_monitors!(nodes[1], 1);
6470
6471         // This causes the HTLC to be failed backwards.
6472         let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6473         assert_eq!(fail_event.len(), 1);
6474         let (fail_msg, commitment_signed) = match &fail_event[0] {
6475                 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6476                         assert_eq!(updates.update_add_htlcs.len(), 0);
6477                         assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6478                         assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6479                         assert_eq!(updates.update_fail_htlcs.len(), 1);
6480                         (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6481                 },
6482                 _ => panic!("Unexpected event"),
6483         };
6484
6485         // Pass the failure messages back to nodes[0].
6486         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6487         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6488
6489         // Complete the HTLC failure+removal process.
6490         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6491         check_added_monitors!(nodes[0], 1);
6492         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6493         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6494         check_added_monitors!(nodes[1], 2);
6495         let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6496         assert_eq!(final_raa_event.len(), 1);
6497         let raa = match &final_raa_event[0] {
6498                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6499                 _ => panic!("Unexpected event"),
6500         };
6501         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6502         expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6503         check_added_monitors!(nodes[0], 1);
6504 }
6505
6506 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6507 // 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.
6508 //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.
6509
6510 #[test]
6511 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6512         //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6513         let chanmon_cfgs = create_chanmon_cfgs(2);
6514         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6515         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6516         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6517         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6518
6519         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6520         route.paths[0][0].fee_msat = 100;
6521
6522         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 },
6523                 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6524         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6525         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6526 }
6527
6528 #[test]
6529 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6530         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6531         let chanmon_cfgs = create_chanmon_cfgs(2);
6532         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6533         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6534         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6535         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6536
6537         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6538         route.paths[0][0].fee_msat = 0;
6539         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 },
6540                 assert_eq!(err, "Cannot send 0-msat HTLC"));
6541
6542         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6543         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6544 }
6545
6546 #[test]
6547 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6548         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6549         let chanmon_cfgs = create_chanmon_cfgs(2);
6550         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6551         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6552         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6553         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6554
6555         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6556         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6557         check_added_monitors!(nodes[0], 1);
6558         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6559         updates.update_add_htlcs[0].amount_msat = 0;
6560
6561         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6562         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6563         check_closed_broadcast!(nodes[1], true).unwrap();
6564         check_added_monitors!(nodes[1], 1);
6565         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
6566 }
6567
6568 #[test]
6569 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6570         //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6571         //It is enforced when constructing a route.
6572         let chanmon_cfgs = create_chanmon_cfgs(2);
6573         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6574         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6575         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6576         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6577
6578         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
6579                 .with_features(channelmanager::provided_invoice_features());
6580         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000, 0);
6581         route.paths[0].last_mut().unwrap().cltv_expiry_delta = 500000001;
6582         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 },
6583                 assert_eq!(err, &"Channel CLTV overflowed?"));
6584 }
6585
6586 #[test]
6587 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6588         //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.
6589         //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6590         //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6591         let chanmon_cfgs = create_chanmon_cfgs(2);
6592         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6593         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6594         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6595         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6596         let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6597
6598         for i in 0..max_accepted_htlcs {
6599                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6600                 let payment_event = {
6601                         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6602                         check_added_monitors!(nodes[0], 1);
6603
6604                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6605                         assert_eq!(events.len(), 1);
6606                         if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6607                                 assert_eq!(htlcs[0].htlc_id, i);
6608                         } else {
6609                                 assert!(false);
6610                         }
6611                         SendEvent::from_event(events.remove(0))
6612                 };
6613                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6614                 check_added_monitors!(nodes[1], 0);
6615                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6616
6617                 expect_pending_htlcs_forwardable!(nodes[1]);
6618                 expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6619         }
6620         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6621         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 },
6622                 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6623
6624         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6625         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6626 }
6627
6628 #[test]
6629 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6630         //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.
6631         let chanmon_cfgs = create_chanmon_cfgs(2);
6632         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6633         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6634         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6635         let channel_value = 100000;
6636         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6637         let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6638
6639         send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6640
6641         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6642         // Manually create a route over our max in flight (which our router normally automatically
6643         // limits us to.
6644         route.paths[0][0].fee_msat =  max_in_flight + 1;
6645         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 },
6646                 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)));
6647
6648         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6649         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);
6650
6651         send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6652 }
6653
6654 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6655 #[test]
6656 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6657         //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6658         let chanmon_cfgs = create_chanmon_cfgs(2);
6659         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6660         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6661         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6662         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6663         let htlc_minimum_msat: u64;
6664         {
6665                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6666                 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6667                 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6668         }
6669
6670         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6671         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6672         check_added_monitors!(nodes[0], 1);
6673         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6674         updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6675         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6676         assert!(nodes[1].node.list_channels().is_empty());
6677         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6678         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()));
6679         check_added_monitors!(nodes[1], 1);
6680         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6681 }
6682
6683 #[test]
6684 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6685         //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
6686         let chanmon_cfgs = create_chanmon_cfgs(2);
6687         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6688         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6689         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6690         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6691
6692         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6693         let channel_reserve = chan_stat.channel_reserve_msat;
6694         let feerate = get_feerate!(nodes[0], chan.2);
6695         let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6696         // The 2* and +1 are for the fee spike reserve.
6697         let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6698
6699         let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6700         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6701         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6702         check_added_monitors!(nodes[0], 1);
6703         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6704
6705         // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6706         // at this time channel-initiatee receivers are not required to enforce that senders
6707         // respect the fee_spike_reserve.
6708         updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6709         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6710
6711         assert!(nodes[1].node.list_channels().is_empty());
6712         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6713         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6714         check_added_monitors!(nodes[1], 1);
6715         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6716 }
6717
6718 #[test]
6719 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6720         //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6721         //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6722         let chanmon_cfgs = create_chanmon_cfgs(2);
6723         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6724         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6725         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6726         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6727
6728         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3999999);
6729         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6730         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6731         let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6732         let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &Some(our_payment_secret), cur_height, &None).unwrap();
6733         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6734
6735         let mut msg = msgs::UpdateAddHTLC {
6736                 channel_id: chan.2,
6737                 htlc_id: 0,
6738                 amount_msat: 1000,
6739                 payment_hash: our_payment_hash,
6740                 cltv_expiry: htlc_cltv,
6741                 onion_routing_packet: onion_packet.clone(),
6742         };
6743
6744         for i in 0..super::channel::OUR_MAX_HTLCS {
6745                 msg.htlc_id = i as u64;
6746                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6747         }
6748         msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6749         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6750
6751         assert!(nodes[1].node.list_channels().is_empty());
6752         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6753         assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6754         check_added_monitors!(nodes[1], 1);
6755         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6756 }
6757
6758 #[test]
6759 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6760         //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6761         let chanmon_cfgs = create_chanmon_cfgs(2);
6762         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6763         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6764         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6765         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6766
6767         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6768         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6769         check_added_monitors!(nodes[0], 1);
6770         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6771         updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6772         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6773
6774         assert!(nodes[1].node.list_channels().is_empty());
6775         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6776         assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6777         check_added_monitors!(nodes[1], 1);
6778         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6779 }
6780
6781 #[test]
6782 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6783         //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6784         let chanmon_cfgs = create_chanmon_cfgs(2);
6785         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6786         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6787         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6788
6789         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6790         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6791         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6792         check_added_monitors!(nodes[0], 1);
6793         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6794         updates.update_add_htlcs[0].cltv_expiry = 500000000;
6795         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6796
6797         assert!(nodes[1].node.list_channels().is_empty());
6798         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6799         assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6800         check_added_monitors!(nodes[1], 1);
6801         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6802 }
6803
6804 #[test]
6805 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6806         //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6807         // We test this by first testing that that repeated HTLCs pass commitment signature checks
6808         // after disconnect and that non-sequential htlc_ids result in a channel failure.
6809         let chanmon_cfgs = create_chanmon_cfgs(2);
6810         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6811         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6812         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6813
6814         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6815         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6816         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6817         check_added_monitors!(nodes[0], 1);
6818         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6819         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6820
6821         //Disconnect and Reconnect
6822         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6823         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6824         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
6825         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6826         assert_eq!(reestablish_1.len(), 1);
6827         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
6828         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6829         assert_eq!(reestablish_2.len(), 1);
6830         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6831         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6832         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6833         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6834
6835         //Resend HTLC
6836         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6837         assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6838         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6839         check_added_monitors!(nodes[1], 1);
6840         let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6841
6842         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6843
6844         assert!(nodes[1].node.list_channels().is_empty());
6845         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6846         assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6847         check_added_monitors!(nodes[1], 1);
6848         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6849 }
6850
6851 #[test]
6852 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6853         //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.
6854
6855         let chanmon_cfgs = create_chanmon_cfgs(2);
6856         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6857         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6858         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6859         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6860         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6861         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6862
6863         check_added_monitors!(nodes[0], 1);
6864         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6865         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6866
6867         let update_msg = msgs::UpdateFulfillHTLC{
6868                 channel_id: chan.2,
6869                 htlc_id: 0,
6870                 payment_preimage: our_payment_preimage,
6871         };
6872
6873         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6874
6875         assert!(nodes[0].node.list_channels().is_empty());
6876         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6877         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()));
6878         check_added_monitors!(nodes[0], 1);
6879         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6880 }
6881
6882 #[test]
6883 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6884         //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.
6885
6886         let chanmon_cfgs = create_chanmon_cfgs(2);
6887         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6888         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6889         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6890         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6891
6892         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6893         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6894         check_added_monitors!(nodes[0], 1);
6895         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6896         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6897
6898         let update_msg = msgs::UpdateFailHTLC{
6899                 channel_id: chan.2,
6900                 htlc_id: 0,
6901                 reason: msgs::OnionErrorPacket { data: Vec::new()},
6902         };
6903
6904         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6905
6906         assert!(nodes[0].node.list_channels().is_empty());
6907         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6908         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()));
6909         check_added_monitors!(nodes[0], 1);
6910         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6911 }
6912
6913 #[test]
6914 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6915         //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.
6916
6917         let chanmon_cfgs = create_chanmon_cfgs(2);
6918         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6919         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6920         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6921         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6922
6923         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6924         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6925         check_added_monitors!(nodes[0], 1);
6926         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6927         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6928         let update_msg = msgs::UpdateFailMalformedHTLC{
6929                 channel_id: chan.2,
6930                 htlc_id: 0,
6931                 sha256_of_onion: [1; 32],
6932                 failure_code: 0x8000,
6933         };
6934
6935         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6936
6937         assert!(nodes[0].node.list_channels().is_empty());
6938         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6939         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()));
6940         check_added_monitors!(nodes[0], 1);
6941         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6942 }
6943
6944 #[test]
6945 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6946         //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6947
6948         let chanmon_cfgs = create_chanmon_cfgs(2);
6949         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6950         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6951         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6952         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6953
6954         let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6955
6956         nodes[1].node.claim_funds(our_payment_preimage);
6957         check_added_monitors!(nodes[1], 1);
6958         expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6959
6960         let events = nodes[1].node.get_and_clear_pending_msg_events();
6961         assert_eq!(events.len(), 1);
6962         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6963                 match events[0] {
6964                         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, .. } } => {
6965                                 assert!(update_add_htlcs.is_empty());
6966                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6967                                 assert!(update_fail_htlcs.is_empty());
6968                                 assert!(update_fail_malformed_htlcs.is_empty());
6969                                 assert!(update_fee.is_none());
6970                                 update_fulfill_htlcs[0].clone()
6971                         },
6972                         _ => panic!("Unexpected event"),
6973                 }
6974         };
6975
6976         update_fulfill_msg.htlc_id = 1;
6977
6978         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6979
6980         assert!(nodes[0].node.list_channels().is_empty());
6981         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6982         assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6983         check_added_monitors!(nodes[0], 1);
6984         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6985 }
6986
6987 #[test]
6988 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6989         //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.
6990
6991         let chanmon_cfgs = create_chanmon_cfgs(2);
6992         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6993         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6994         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6995         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6996
6997         let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6998
6999         nodes[1].node.claim_funds(our_payment_preimage);
7000         check_added_monitors!(nodes[1], 1);
7001         expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
7002
7003         let events = nodes[1].node.get_and_clear_pending_msg_events();
7004         assert_eq!(events.len(), 1);
7005         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
7006                 match events[0] {
7007                         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, .. } } => {
7008                                 assert!(update_add_htlcs.is_empty());
7009                                 assert_eq!(update_fulfill_htlcs.len(), 1);
7010                                 assert!(update_fail_htlcs.is_empty());
7011                                 assert!(update_fail_malformed_htlcs.is_empty());
7012                                 assert!(update_fee.is_none());
7013                                 update_fulfill_htlcs[0].clone()
7014                         },
7015                         _ => panic!("Unexpected event"),
7016                 }
7017         };
7018
7019         update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
7020
7021         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
7022
7023         assert!(nodes[0].node.list_channels().is_empty());
7024         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
7025         assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
7026         check_added_monitors!(nodes[0], 1);
7027         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
7028 }
7029
7030 #[test]
7031 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
7032         //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.
7033
7034         let chanmon_cfgs = create_chanmon_cfgs(2);
7035         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7036         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7037         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7038         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7039
7040         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
7041         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
7042         check_added_monitors!(nodes[0], 1);
7043
7044         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7045         updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
7046
7047         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
7048         check_added_monitors!(nodes[1], 0);
7049         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
7050
7051         let events = nodes[1].node.get_and_clear_pending_msg_events();
7052
7053         let mut update_msg: msgs::UpdateFailMalformedHTLC = {
7054                 match events[0] {
7055                         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, .. } } => {
7056                                 assert!(update_add_htlcs.is_empty());
7057                                 assert!(update_fulfill_htlcs.is_empty());
7058                                 assert!(update_fail_htlcs.is_empty());
7059                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
7060                                 assert!(update_fee.is_none());
7061                                 update_fail_malformed_htlcs[0].clone()
7062                         },
7063                         _ => panic!("Unexpected event"),
7064                 }
7065         };
7066         update_msg.failure_code &= !0x8000;
7067         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
7068
7069         assert!(nodes[0].node.list_channels().is_empty());
7070         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
7071         assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
7072         check_added_monitors!(nodes[0], 1);
7073         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
7074 }
7075
7076 #[test]
7077 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
7078         //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
7079         //    * 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.
7080
7081         let chanmon_cfgs = create_chanmon_cfgs(3);
7082         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7083         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7084         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7085         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7086         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7087
7088         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
7089
7090         //First hop
7091         let mut payment_event = {
7092                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
7093                 check_added_monitors!(nodes[0], 1);
7094                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7095                 assert_eq!(events.len(), 1);
7096                 SendEvent::from_event(events.remove(0))
7097         };
7098         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7099         check_added_monitors!(nodes[1], 0);
7100         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7101         expect_pending_htlcs_forwardable!(nodes[1]);
7102         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7103         assert_eq!(events_2.len(), 1);
7104         check_added_monitors!(nodes[1], 1);
7105         payment_event = SendEvent::from_event(events_2.remove(0));
7106         assert_eq!(payment_event.msgs.len(), 1);
7107
7108         //Second Hop
7109         payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
7110         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
7111         check_added_monitors!(nodes[2], 0);
7112         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
7113
7114         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
7115         assert_eq!(events_3.len(), 1);
7116         let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
7117                 match events_3[0] {
7118                         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 } } => {
7119                                 assert!(update_add_htlcs.is_empty());
7120                                 assert!(update_fulfill_htlcs.is_empty());
7121                                 assert!(update_fail_htlcs.is_empty());
7122                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
7123                                 assert!(update_fee.is_none());
7124                                 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
7125                         },
7126                         _ => panic!("Unexpected event"),
7127                 }
7128         };
7129
7130         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
7131
7132         check_added_monitors!(nodes[1], 0);
7133         commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
7134         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 }]);
7135         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
7136         assert_eq!(events_4.len(), 1);
7137
7138         //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
7139         match events_4[0] {
7140                 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, .. } } => {
7141                         assert!(update_add_htlcs.is_empty());
7142                         assert!(update_fulfill_htlcs.is_empty());
7143                         assert_eq!(update_fail_htlcs.len(), 1);
7144                         assert!(update_fail_malformed_htlcs.is_empty());
7145                         assert!(update_fee.is_none());
7146                 },
7147                 _ => panic!("Unexpected event"),
7148         };
7149
7150         check_added_monitors!(nodes[1], 1);
7151 }
7152
7153 #[test]
7154 fn test_channel_failed_after_message_with_badonion_node_perm_bits_set() {
7155         let chanmon_cfgs = create_chanmon_cfgs(3);
7156         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7157         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7158         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7159         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7160         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7161
7162         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100_000);
7163
7164         // First hop
7165         let mut payment_event = {
7166                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
7167                 check_added_monitors!(nodes[0], 1);
7168                 SendEvent::from_node(&nodes[0])
7169         };
7170
7171         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7172         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7173         expect_pending_htlcs_forwardable!(nodes[1]);
7174         check_added_monitors!(nodes[1], 1);
7175         payment_event = SendEvent::from_node(&nodes[1]);
7176         assert_eq!(payment_event.msgs.len(), 1);
7177
7178         // Second Hop
7179         payment_event.msgs[0].onion_routing_packet.version = 1; // Trigger an invalid_onion_version error
7180         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
7181         check_added_monitors!(nodes[2], 0);
7182         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
7183
7184         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
7185         assert_eq!(events_3.len(), 1);
7186         match events_3[0] {
7187                 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
7188                         let mut update_msg = updates.update_fail_malformed_htlcs[0].clone();
7189                         // Set the NODE bit (BADONION and PERM already set in invalid_onion_version error)
7190                         update_msg.failure_code |= 0x2000;
7191
7192                         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg);
7193                         commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true);
7194                 },
7195                 _ => panic!("Unexpected event"),
7196         }
7197
7198         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
7199                 vec![HTLCDestination::NextHopChannel {
7200                         node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
7201         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
7202         assert_eq!(events_4.len(), 1);
7203         check_added_monitors!(nodes[1], 1);
7204
7205         match events_4[0] {
7206                 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
7207                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
7208                         commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
7209                 },
7210                 _ => panic!("Unexpected event"),
7211         }
7212
7213         let events_5 = nodes[0].node.get_and_clear_pending_events();
7214         assert_eq!(events_5.len(), 1);
7215
7216         // Expect a PaymentPathFailed event with a ChannelFailure network update for the channel between
7217         // the node originating the error to its next hop.
7218         match events_5[0] {
7219                 Event::PaymentPathFailed { network_update:
7220                         Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent }), error_code, ..
7221                 } => {
7222                         assert_eq!(short_channel_id, chan_2.0.contents.short_channel_id);
7223                         assert!(is_permanent);
7224                         assert_eq!(error_code, Some(0x8000|0x4000|0x2000|4));
7225                 },
7226                 _ => panic!("Unexpected event"),
7227         }
7228
7229         // TODO: Test actual removal of channel from NetworkGraph when it's implemented.
7230 }
7231
7232 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
7233         // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
7234         // 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
7235         // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
7236
7237         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7238         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7239         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7240         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7241         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7242         let chan =create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7243
7244         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7245
7246         // We route 2 dust-HTLCs between A and B
7247         let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7248         let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7249         route_payment(&nodes[0], &[&nodes[1]], 1000000);
7250
7251         // Cache one local commitment tx as previous
7252         let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7253
7254         // Fail one HTLC to prune it in the will-be-latest-local commitment tx
7255         nodes[1].node.fail_htlc_backwards(&payment_hash_2);
7256         check_added_monitors!(nodes[1], 0);
7257         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
7258         check_added_monitors!(nodes[1], 1);
7259
7260         let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7261         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
7262         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
7263         check_added_monitors!(nodes[0], 1);
7264
7265         // Cache one local commitment tx as lastest
7266         let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7267
7268         let events = nodes[0].node.get_and_clear_pending_msg_events();
7269         match events[0] {
7270                 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
7271                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7272                 },
7273                 _ => panic!("Unexpected event"),
7274         }
7275         match events[1] {
7276                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
7277                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7278                 },
7279                 _ => panic!("Unexpected event"),
7280         }
7281
7282         assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
7283         // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7284         if announce_latest {
7285                 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
7286         } else {
7287                 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
7288         }
7289
7290         check_closed_broadcast!(nodes[0], true);
7291         check_added_monitors!(nodes[0], 1);
7292         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7293
7294         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7295         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7296         let events = nodes[0].node.get_and_clear_pending_events();
7297         // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
7298         assert_eq!(events.len(), 2);
7299         let mut first_failed = false;
7300         for event in events {
7301                 match event {
7302                         Event::PaymentPathFailed { payment_hash, .. } => {
7303                                 if payment_hash == payment_hash_1 {
7304                                         assert!(!first_failed);
7305                                         first_failed = true;
7306                                 } else {
7307                                         assert_eq!(payment_hash, payment_hash_2);
7308                                 }
7309                         }
7310                         _ => panic!("Unexpected event"),
7311                 }
7312         }
7313 }
7314
7315 #[test]
7316 fn test_failure_delay_dust_htlc_local_commitment() {
7317         do_test_failure_delay_dust_htlc_local_commitment(true);
7318         do_test_failure_delay_dust_htlc_local_commitment(false);
7319 }
7320
7321 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7322         // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7323         // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7324         // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7325         // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7326         // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7327         // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7328
7329         let chanmon_cfgs = create_chanmon_cfgs(3);
7330         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7331         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7332         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7333         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7334
7335         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7336
7337         let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7338         let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7339
7340         let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7341         let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7342
7343         // We revoked bs_commitment_tx
7344         if revoked {
7345                 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7346                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
7347         }
7348
7349         let mut timeout_tx = Vec::new();
7350         if local {
7351                 // We fail dust-HTLC 1 by broadcast of local commitment tx
7352                 mine_transaction(&nodes[0], &as_commitment_tx[0]);
7353                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7354                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7355                 expect_payment_failed!(nodes[0], dust_hash, false);
7356
7357                 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
7358                 check_closed_broadcast!(nodes[0], true);
7359                 check_added_monitors!(nodes[0], 1);
7360                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7361                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
7362                 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7363                 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7364                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7365                 mine_transaction(&nodes[0], &timeout_tx[0]);
7366                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7367                 expect_payment_failed!(nodes[0], non_dust_hash, false);
7368         } else {
7369                 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7370                 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
7371                 check_closed_broadcast!(nodes[0], true);
7372                 check_added_monitors!(nodes[0], 1);
7373                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7374                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7375
7376                 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7377                 timeout_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().drain(..)
7378                         .filter(|tx| tx.input[0].previous_output.txid == bs_commitment_tx[0].txid()).collect();
7379                 check_spends!(timeout_tx[0], bs_commitment_tx[0]);
7380                 // For both a revoked or non-revoked commitment transaction, after ANTI_REORG_DELAY the
7381                 // dust HTLC should have been failed.
7382                 expect_payment_failed!(nodes[0], dust_hash, false);
7383
7384                 if !revoked {
7385                         assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7386                 } else {
7387                         assert_eq!(timeout_tx[0].lock_time.0, 0);
7388                 }
7389                 // We fail non-dust-HTLC 2 by broadcast of local timeout/revocation-claim tx
7390                 mine_transaction(&nodes[0], &timeout_tx[0]);
7391                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7392                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7393                 expect_payment_failed!(nodes[0], non_dust_hash, false);
7394         }
7395 }
7396
7397 #[test]
7398 fn test_sweep_outbound_htlc_failure_update() {
7399         do_test_sweep_outbound_htlc_failure_update(false, true);
7400         do_test_sweep_outbound_htlc_failure_update(false, false);
7401         do_test_sweep_outbound_htlc_failure_update(true, false);
7402 }
7403
7404 #[test]
7405 fn test_user_configurable_csv_delay() {
7406         // We test our channel constructors yield errors when we pass them absurd csv delay
7407
7408         let mut low_our_to_self_config = UserConfig::default();
7409         low_our_to_self_config.channel_handshake_config.our_to_self_delay = 6;
7410         let mut high_their_to_self_config = UserConfig::default();
7411         high_their_to_self_config.channel_handshake_limits.their_to_self_delay = 100;
7412         let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7413         let chanmon_cfgs = create_chanmon_cfgs(2);
7414         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7415         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7416         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7417
7418         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7419         if let Err(error) = Channel::new_outbound(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7420                 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &channelmanager::provided_init_features(), 1000000, 1000000, 0,
7421                 &low_our_to_self_config, 0, 42)
7422         {
7423                 match error {
7424                         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())); },
7425                         _ => panic!("Unexpected event"),
7426                 }
7427         } else { assert!(false) }
7428
7429         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7430         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7431         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7432         open_channel.to_self_delay = 200;
7433         if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7434                 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &channelmanager::provided_init_features(), &open_channel, 0,
7435                 &low_our_to_self_config, 0, &nodes[0].logger, 42)
7436         {
7437                 match error {
7438                         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()));  },
7439                         _ => panic!("Unexpected event"),
7440                 }
7441         } else { assert!(false); }
7442
7443         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7444         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7445         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()));
7446         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7447         accept_channel.to_self_delay = 200;
7448         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_channel);
7449         let reason_msg;
7450         if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7451                 match action {
7452                         &ErrorAction::SendErrorMessage { ref msg } => {
7453                                 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()));
7454                                 reason_msg = msg.data.clone();
7455                         },
7456                         _ => { panic!(); }
7457                 }
7458         } else { panic!(); }
7459         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg });
7460
7461         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7462         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7463         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7464         open_channel.to_self_delay = 200;
7465         if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7466                 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &channelmanager::provided_init_features(), &open_channel, 0,
7467                 &high_their_to_self_config, 0, &nodes[0].logger, 42)
7468         {
7469                 match error {
7470                         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())); },
7471                         _ => panic!("Unexpected event"),
7472                 }
7473         } else { assert!(false); }
7474 }
7475
7476 fn do_test_data_loss_protect(reconnect_panicing: bool) {
7477         // When we get a data_loss_protect proving we're behind, we immediately panic as the
7478         // chain::Watch API requirements have been violated (e.g. the user restored from a backup). The
7479         // panic message informs the user they should force-close without broadcasting, which is tested
7480         // if `reconnect_panicing` is not set.
7481         let persister;
7482         let logger;
7483         let fee_estimator;
7484         let tx_broadcaster;
7485         let chain_source;
7486         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7487         // We broadcast during Drop because chanmon is out of sync with chanmgr, which would cause a panic
7488         // during signing due to revoked tx
7489         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7490         let keys_manager = &chanmon_cfgs[0].keys_manager;
7491         let monitor;
7492         let node_state_0;
7493         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7494         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7495         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7496
7497         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7498
7499         // Cache node A state before any channel update
7500         let previous_node_state = nodes[0].node.encode();
7501         let mut previous_chain_monitor_state = test_utils::TestVecWriter(Vec::new());
7502         get_monitor!(nodes[0], chan.2).write(&mut previous_chain_monitor_state).unwrap();
7503
7504         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7505         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7506
7507         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7508         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7509
7510         // Restore node A from previous state
7511         logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7512         let mut chain_monitor = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut io::Cursor::new(previous_chain_monitor_state.0), keys_manager).unwrap().1;
7513         chain_source = test_utils::TestChainSource::new(Network::Testnet);
7514         tx_broadcaster = test_utils::TestBroadcaster { txn_broadcasted: Mutex::new(Vec::new()), blocks: Arc::new(Mutex::new(Vec::new())) };
7515         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
7516         persister = test_utils::TestPersister::new();
7517         monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &tx_broadcaster, &logger, &fee_estimator, &persister, keys_manager);
7518         node_state_0 = {
7519                 let mut channel_monitors = HashMap::new();
7520                 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chain_monitor);
7521                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut io::Cursor::new(previous_node_state), ChannelManagerReadArgs {
7522                         keys_manager: keys_manager,
7523                         fee_estimator: &fee_estimator,
7524                         chain_monitor: &monitor,
7525                         logger: &logger,
7526                         tx_broadcaster: &tx_broadcaster,
7527                         default_config: UserConfig::default(),
7528                         channel_monitors,
7529                 }).unwrap().1
7530         };
7531         nodes[0].node = &node_state_0;
7532         assert_eq!(monitor.watch_channel(OutPoint { txid: chan.3.txid(), index: 0 }, chain_monitor),
7533                 ChannelMonitorUpdateStatus::Completed);
7534         nodes[0].chain_monitor = &monitor;
7535         nodes[0].chain_source = &chain_source;
7536
7537         check_added_monitors!(nodes[0], 1);
7538
7539         if reconnect_panicing {
7540                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
7541                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
7542
7543                 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7544
7545                 // Check we close channel detecting A is fallen-behind
7546                 // Check that we sent the warning message when we detected that A has fallen behind,
7547                 // and give the possibility for A to recover from the warning.
7548                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7549                 let warn_msg = "Peer attempted to reestablish channel with a very old local commitment transaction".to_owned();
7550                 assert!(check_warn_msg!(nodes[1], nodes[0].node.get_our_node_id(), chan.2).contains(&warn_msg));
7551
7552                 {
7553                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7554                         // The node B should not broadcast the transaction to force close the channel!
7555                         assert!(node_txn.is_empty());
7556                 }
7557
7558                 let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7559                 // Check A panics upon seeing proof it has fallen behind.
7560                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7561                 return; // By this point we should have panic'ed!
7562         }
7563
7564         nodes[0].node.force_close_without_broadcasting_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
7565         check_added_monitors!(nodes[0], 1);
7566         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
7567         {
7568                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7569                 assert_eq!(node_txn.len(), 0);
7570         }
7571
7572         for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7573                 if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7574                 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7575                         match action {
7576                                 &ErrorAction::SendErrorMessage { ref msg } => {
7577                                         assert_eq!(msg.data, "Channel force-closed");
7578                                 },
7579                                 _ => panic!("Unexpected event!"),
7580                         }
7581                 } else {
7582                         panic!("Unexpected event {:?}", msg)
7583                 }
7584         }
7585
7586         // after the warning message sent by B, we should not able to
7587         // use the channel, or reconnect with success to the channel.
7588         assert!(nodes[0].node.list_usable_channels().is_empty());
7589         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
7590         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
7591         let retry_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7592
7593         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &retry_reestablish[0]);
7594         let mut err_msgs_0 = Vec::with_capacity(1);
7595         for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7596                 if let MessageSendEvent::HandleError { ref action, .. } = msg {
7597                         match action {
7598                                 &ErrorAction::SendErrorMessage { ref msg } => {
7599                                         assert_eq!(msg.data, "Failed to find corresponding channel");
7600                                         err_msgs_0.push(msg.clone());
7601                                 },
7602                                 _ => panic!("Unexpected event!"),
7603                         }
7604                 } else {
7605                         panic!("Unexpected event!");
7606                 }
7607         }
7608         assert_eq!(err_msgs_0.len(), 1);
7609         nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), &err_msgs_0[0]);
7610         assert!(nodes[1].node.list_usable_channels().is_empty());
7611         check_added_monitors!(nodes[1], 1);
7612         check_closed_event!(nodes[1], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "Failed to find corresponding channel".to_owned() });
7613         check_closed_broadcast!(nodes[1], false);
7614 }
7615
7616 #[test]
7617 #[should_panic]
7618 fn test_data_loss_protect_showing_stale_state_panics() {
7619         do_test_data_loss_protect(true);
7620 }
7621
7622 #[test]
7623 fn test_force_close_without_broadcast() {
7624         do_test_data_loss_protect(false);
7625 }
7626
7627 #[test]
7628 fn test_check_htlc_underpaying() {
7629         // Send payment through A -> B but A is maliciously
7630         // sending a probe payment (i.e less than expected value0
7631         // to B, B should refuse payment.
7632
7633         let chanmon_cfgs = create_chanmon_cfgs(2);
7634         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7635         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7636         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7637
7638         // Create some initial channels
7639         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7640
7641         let scorer = test_utils::TestScorer::with_penalty(0);
7642         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7643         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id()).with_features(channelmanager::provided_invoice_features());
7644         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();
7645         let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7646         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200).unwrap();
7647         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
7648         check_added_monitors!(nodes[0], 1);
7649
7650         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7651         assert_eq!(events.len(), 1);
7652         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7653         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7654         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7655
7656         // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7657         // and then will wait a second random delay before failing the HTLC back:
7658         expect_pending_htlcs_forwardable!(nodes[1]);
7659         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
7660
7661         // Node 3 is expecting payment of 100_000 but received 10_000,
7662         // it should fail htlc like we didn't know the preimage.
7663         nodes[1].node.process_pending_htlc_forwards();
7664
7665         let events = nodes[1].node.get_and_clear_pending_msg_events();
7666         assert_eq!(events.len(), 1);
7667         let (update_fail_htlc, commitment_signed) = match events[0] {
7668                 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 } } => {
7669                         assert!(update_add_htlcs.is_empty());
7670                         assert!(update_fulfill_htlcs.is_empty());
7671                         assert_eq!(update_fail_htlcs.len(), 1);
7672                         assert!(update_fail_malformed_htlcs.is_empty());
7673                         assert!(update_fee.is_none());
7674                         (update_fail_htlcs[0].clone(), commitment_signed)
7675                 },
7676                 _ => panic!("Unexpected event"),
7677         };
7678         check_added_monitors!(nodes[1], 1);
7679
7680         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7681         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7682
7683         // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7684         let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7685         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(CHAN_CONFIRM_DEPTH));
7686         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7687 }
7688
7689 #[test]
7690 fn test_announce_disable_channels() {
7691         // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7692         // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7693
7694         let chanmon_cfgs = create_chanmon_cfgs(2);
7695         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7696         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7697         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7698
7699         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7700         create_announced_chan_between_nodes(&nodes, 1, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7701         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7702
7703         // Disconnect peers
7704         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7705         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7706
7707         nodes[0].node.timer_tick_occurred(); // Enabled -> DisabledStaged
7708         nodes[0].node.timer_tick_occurred(); // DisabledStaged -> Disabled
7709         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7710         assert_eq!(msg_events.len(), 3);
7711         let mut chans_disabled = HashMap::new();
7712         for e in msg_events {
7713                 match e {
7714                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7715                                 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7716                                 // Check that each channel gets updated exactly once
7717                                 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7718                                         panic!("Generated ChannelUpdate for wrong chan!");
7719                                 }
7720                         },
7721                         _ => panic!("Unexpected event"),
7722                 }
7723         }
7724         // Reconnect peers
7725         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
7726         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7727         assert_eq!(reestablish_1.len(), 3);
7728         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
7729         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7730         assert_eq!(reestablish_2.len(), 3);
7731
7732         // Reestablish chan_1
7733         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7734         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7735         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7736         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7737         // Reestablish chan_2
7738         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7739         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7740         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7741         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7742         // Reestablish chan_3
7743         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7744         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7745         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7746         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7747
7748         nodes[0].node.timer_tick_occurred();
7749         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7750         nodes[0].node.timer_tick_occurred();
7751         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7752         assert_eq!(msg_events.len(), 3);
7753         for e in msg_events {
7754                 match e {
7755                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7756                                 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7757                                 match chans_disabled.remove(&msg.contents.short_channel_id) {
7758                                         // Each update should have a higher timestamp than the previous one, replacing
7759                                         // the old one.
7760                                         Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7761                                         None => panic!("Generated ChannelUpdate for wrong chan!"),
7762                                 }
7763                         },
7764                         _ => panic!("Unexpected event"),
7765                 }
7766         }
7767         // Check that each channel gets updated exactly once
7768         assert!(chans_disabled.is_empty());
7769 }
7770
7771 #[test]
7772 fn test_bump_penalty_txn_on_revoked_commitment() {
7773         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7774         // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7775
7776         let chanmon_cfgs = create_chanmon_cfgs(2);
7777         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7778         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7779         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7780
7781         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7782
7783         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7784         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id())
7785                 .with_features(channelmanager::provided_invoice_features());
7786         let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000, 30);
7787         send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7788
7789         let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7790         // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7791         assert_eq!(revoked_txn[0].output.len(), 4);
7792         assert_eq!(revoked_txn[0].input.len(), 1);
7793         assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7794         let revoked_txid = revoked_txn[0].txid();
7795
7796         let mut penalty_sum = 0;
7797         for outp in revoked_txn[0].output.iter() {
7798                 if outp.script_pubkey.is_v0_p2wsh() {
7799                         penalty_sum += outp.value;
7800                 }
7801         }
7802
7803         // Connect blocks to change height_timer range to see if we use right soonest_timelock
7804         let header_114 = connect_blocks(&nodes[1], 14);
7805
7806         // Actually revoke tx by claiming a HTLC
7807         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7808         let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7809         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] });
7810         check_added_monitors!(nodes[1], 1);
7811
7812         // One or more justice tx should have been broadcast, check it
7813         let penalty_1;
7814         let feerate_1;
7815         {
7816                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7817                 assert_eq!(node_txn.len(), 2); // justice tx (broadcasted from ChannelMonitor) + local commitment tx
7818                 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7819                 assert_eq!(node_txn[0].output.len(), 1);
7820                 check_spends!(node_txn[0], revoked_txn[0]);
7821                 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7822                 feerate_1 = fee_1 * 1000 / node_txn[0].weight() as u64;
7823                 penalty_1 = node_txn[0].txid();
7824                 node_txn.clear();
7825         };
7826
7827         // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7828         connect_blocks(&nodes[1], 15);
7829         let mut penalty_2 = penalty_1;
7830         let mut feerate_2 = 0;
7831         {
7832                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7833                 assert_eq!(node_txn.len(), 1);
7834                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7835                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7836                         assert_eq!(node_txn[0].output.len(), 1);
7837                         check_spends!(node_txn[0], revoked_txn[0]);
7838                         penalty_2 = node_txn[0].txid();
7839                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7840                         assert_ne!(penalty_2, penalty_1);
7841                         let fee_2 = penalty_sum - node_txn[0].output[0].value;
7842                         feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7843                         // Verify 25% bump heuristic
7844                         assert!(feerate_2 * 100 >= feerate_1 * 125);
7845                         node_txn.clear();
7846                 }
7847         }
7848         assert_ne!(feerate_2, 0);
7849
7850         // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7851         connect_blocks(&nodes[1], 1);
7852         let penalty_3;
7853         let mut feerate_3 = 0;
7854         {
7855                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7856                 assert_eq!(node_txn.len(), 1);
7857                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7858                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7859                         assert_eq!(node_txn[0].output.len(), 1);
7860                         check_spends!(node_txn[0], revoked_txn[0]);
7861                         penalty_3 = node_txn[0].txid();
7862                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7863                         assert_ne!(penalty_3, penalty_2);
7864                         let fee_3 = penalty_sum - node_txn[0].output[0].value;
7865                         feerate_3 = fee_3 * 1000 / node_txn[0].weight() as u64;
7866                         // Verify 25% bump heuristic
7867                         assert!(feerate_3 * 100 >= feerate_2 * 125);
7868                         node_txn.clear();
7869                 }
7870         }
7871         assert_ne!(feerate_3, 0);
7872
7873         nodes[1].node.get_and_clear_pending_events();
7874         nodes[1].node.get_and_clear_pending_msg_events();
7875 }
7876
7877 #[test]
7878 fn test_bump_penalty_txn_on_revoked_htlcs() {
7879         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7880         // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7881
7882         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7883         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7884         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7885         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7886         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7887
7888         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7889         // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7890         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id()).with_features(channelmanager::provided_invoice_features());
7891         let scorer = test_utils::TestScorer::with_penalty(0);
7892         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7893         let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None,
7894                 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7895         let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7896         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id()).with_features(channelmanager::provided_invoice_features());
7897         let route = get_route(&nodes[1].node.get_our_node_id(), &payment_params, &nodes[1].network_graph.read_only(), None,
7898                 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7899         send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7900
7901         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7902         assert_eq!(revoked_local_txn[0].input.len(), 1);
7903         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7904
7905         // Revoke local commitment tx
7906         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7907
7908         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7909         // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7910         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] });
7911         check_closed_broadcast!(nodes[1], true);
7912         check_added_monitors!(nodes[1], 1);
7913         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7914         connect_blocks(&nodes[1], 49); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7915
7916         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
7917         assert_eq!(revoked_htlc_txn.len(), 3);
7918         check_spends!(revoked_htlc_txn[1], chan.3);
7919
7920         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7921         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7922         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7923
7924         assert_eq!(revoked_htlc_txn[2].input.len(), 1);
7925         assert_eq!(revoked_htlc_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7926         assert_eq!(revoked_htlc_txn[2].output.len(), 1);
7927         check_spends!(revoked_htlc_txn[2], revoked_local_txn[0]);
7928
7929         // Broadcast set of revoked txn on A
7930         let hash_128 = connect_blocks(&nodes[0], 40);
7931         let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7932         connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] });
7933         let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7934         connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[2].clone()] });
7935         let events = nodes[0].node.get_and_clear_pending_events();
7936         expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7937         match events.last().unwrap() {
7938                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7939                 _ => panic!("Unexpected event"),
7940         }
7941         let first;
7942         let feerate_1;
7943         let penalty_txn;
7944         {
7945                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7946                 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7947                 // Verify claim tx are spending revoked HTLC txn
7948
7949                 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7950                 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7951                 // which are included in the same block (they are broadcasted because we scan the
7952                 // transactions linearly and generate claims as we go, they likely should be removed in the
7953                 // future).
7954                 assert_eq!(node_txn[0].input.len(), 1);
7955                 check_spends!(node_txn[0], revoked_local_txn[0]);
7956                 assert_eq!(node_txn[1].input.len(), 1);
7957                 check_spends!(node_txn[1], revoked_local_txn[0]);
7958                 assert_eq!(node_txn[2].input.len(), 1);
7959                 check_spends!(node_txn[2], revoked_local_txn[0]);
7960
7961                 // Each of the three justice transactions claim a separate (single) output of the three
7962                 // available, which we check here:
7963                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7964                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7965                 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7966
7967                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7968                 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7969
7970                 // node_txn[3] is the local commitment tx broadcast just because (and somewhat in case of
7971                 // reorgs, though its not clear its ever worth broadcasting conflicting txn like this when
7972                 // a remote commitment tx has already been confirmed).
7973                 check_spends!(node_txn[3], chan.3);
7974
7975                 // node_txn[4] spends the revoked outputs from the revoked_htlc_txn (which only have one
7976                 // output, checked above).
7977                 assert_eq!(node_txn[4].input.len(), 2);
7978                 assert_eq!(node_txn[4].output.len(), 1);
7979                 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7980
7981                 first = node_txn[4].txid();
7982                 // Store both feerates for later comparison
7983                 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[4].output[0].value;
7984                 feerate_1 = fee_1 * 1000 / node_txn[4].weight() as u64;
7985                 penalty_txn = vec![node_txn[2].clone()];
7986                 node_txn.clear();
7987         }
7988
7989         // Connect one more block to see if bumped penalty are issued for HTLC txn
7990         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7991         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7992         let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7993         connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() });
7994         {
7995                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7996                 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7997
7998                 check_spends!(node_txn[0], revoked_local_txn[0]);
7999                 check_spends!(node_txn[1], revoked_local_txn[0]);
8000                 // Note that these are both bogus - they spend outputs already claimed in block 129:
8001                 if node_txn[0].input[0].previous_output == revoked_htlc_txn[0].input[0].previous_output  {
8002                         assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
8003                 } else {
8004                         assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
8005                         assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
8006                 }
8007
8008                 node_txn.clear();
8009         };
8010
8011         // Few more blocks to confirm penalty txn
8012         connect_blocks(&nodes[0], 4);
8013         assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
8014         let header_144 = connect_blocks(&nodes[0], 9);
8015         let node_txn = {
8016                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8017                 assert_eq!(node_txn.len(), 1);
8018
8019                 assert_eq!(node_txn[0].input.len(), 2);
8020                 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[2]);
8021                 // Verify bumped tx is different and 25% bump heuristic
8022                 assert_ne!(first, node_txn[0].txid());
8023                 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[0].output[0].value;
8024                 let feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
8025                 assert!(feerate_2 * 100 > feerate_1 * 125);
8026                 let txn = vec![node_txn[0].clone()];
8027                 node_txn.clear();
8028                 txn
8029         };
8030         // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
8031         let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8032         connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn });
8033         connect_blocks(&nodes[0], 20);
8034         {
8035                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8036                 // We verify than no new transaction has been broadcast because previously
8037                 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
8038                 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
8039                 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
8040                 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
8041                 // up bumped justice generation.
8042                 assert_eq!(node_txn.len(), 0);
8043                 node_txn.clear();
8044         }
8045         check_closed_broadcast!(nodes[0], true);
8046         check_added_monitors!(nodes[0], 1);
8047 }
8048
8049 #[test]
8050 fn test_bump_penalty_txn_on_remote_commitment() {
8051         // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
8052         // we're able to claim outputs on remote commitment transaction before timelocks expiration
8053
8054         // Create 2 HTLCs
8055         // Provide preimage for one
8056         // Check aggregation
8057
8058         let chanmon_cfgs = create_chanmon_cfgs(2);
8059         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8060         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8061         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8062
8063         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8064         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
8065         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
8066
8067         // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
8068         let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
8069         assert_eq!(remote_txn[0].output.len(), 4);
8070         assert_eq!(remote_txn[0].input.len(), 1);
8071         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
8072
8073         // Claim a HTLC without revocation (provide B monitor with preimage)
8074         nodes[1].node.claim_funds(payment_preimage);
8075         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
8076         mine_transaction(&nodes[1], &remote_txn[0]);
8077         check_added_monitors!(nodes[1], 2);
8078         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
8079
8080         // One or more claim tx should have been broadcast, check it
8081         let timeout;
8082         let preimage;
8083         let preimage_bump;
8084         let feerate_timeout;
8085         let feerate_preimage;
8086         {
8087                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8088                 // 5 transactions including:
8089                 //   local commitment + HTLC-Success
8090                 //   preimage and timeout sweeps from remote commitment + preimage sweep bump
8091                 assert_eq!(node_txn.len(), 5);
8092                 assert_eq!(node_txn[0].input.len(), 1);
8093                 assert_eq!(node_txn[3].input.len(), 1);
8094                 assert_eq!(node_txn[4].input.len(), 1);
8095                 check_spends!(node_txn[0], remote_txn[0]);
8096                 check_spends!(node_txn[3], remote_txn[0]);
8097                 check_spends!(node_txn[4], remote_txn[0]);
8098
8099                 check_spends!(node_txn[1], chan.3); // local commitment
8100                 check_spends!(node_txn[2], node_txn[1]); // local HTLC-Success
8101
8102                 preimage = node_txn[0].txid();
8103                 let index = node_txn[0].input[0].previous_output.vout;
8104                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8105                 feerate_preimage = fee * 1000 / node_txn[0].weight() as u64;
8106
8107                 let (preimage_bump_tx, timeout_tx) = if node_txn[3].input[0].previous_output == node_txn[0].input[0].previous_output {
8108                         (node_txn[3].clone(), node_txn[4].clone())
8109                 } else {
8110                         (node_txn[4].clone(), node_txn[3].clone())
8111                 };
8112
8113                 preimage_bump = preimage_bump_tx;
8114                 check_spends!(preimage_bump, remote_txn[0]);
8115                 assert_eq!(node_txn[0].input[0].previous_output, preimage_bump.input[0].previous_output);
8116
8117                 timeout = timeout_tx.txid();
8118                 let index = timeout_tx.input[0].previous_output.vout;
8119                 let fee = remote_txn[0].output[index as usize].value - timeout_tx.output[0].value;
8120                 feerate_timeout = fee * 1000 / timeout_tx.weight() as u64;
8121
8122                 node_txn.clear();
8123         };
8124         assert_ne!(feerate_timeout, 0);
8125         assert_ne!(feerate_preimage, 0);
8126
8127         // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
8128         connect_blocks(&nodes[1], 15);
8129         {
8130                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8131                 assert_eq!(node_txn.len(), 1);
8132                 assert_eq!(node_txn[0].input.len(), 1);
8133                 assert_eq!(preimage_bump.input.len(), 1);
8134                 check_spends!(node_txn[0], remote_txn[0]);
8135                 check_spends!(preimage_bump, remote_txn[0]);
8136
8137                 let index = preimage_bump.input[0].previous_output.vout;
8138                 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
8139                 let new_feerate = fee * 1000 / preimage_bump.weight() as u64;
8140                 assert!(new_feerate * 100 > feerate_timeout * 125);
8141                 assert_ne!(timeout, preimage_bump.txid());
8142
8143                 let index = node_txn[0].input[0].previous_output.vout;
8144                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8145                 let new_feerate = fee * 1000 / node_txn[0].weight() as u64;
8146                 assert!(new_feerate * 100 > feerate_preimage * 125);
8147                 assert_ne!(preimage, node_txn[0].txid());
8148
8149                 node_txn.clear();
8150         }
8151
8152         nodes[1].node.get_and_clear_pending_events();
8153         nodes[1].node.get_and_clear_pending_msg_events();
8154 }
8155
8156 #[test]
8157 fn test_counterparty_raa_skip_no_crash() {
8158         // Previously, if our counterparty sent two RAAs in a row without us having provided a
8159         // commitment transaction, we would have happily carried on and provided them the next
8160         // commitment transaction based on one RAA forward. This would probably eventually have led to
8161         // channel closure, but it would not have resulted in funds loss. Still, our
8162         // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
8163         // check simply that the channel is closed in response to such an RAA, but don't check whether
8164         // we decide to punish our counterparty for revoking their funds (as we don't currently
8165         // implement that).
8166         let chanmon_cfgs = create_chanmon_cfgs(2);
8167         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8168         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8169         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8170         let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
8171
8172         let per_commitment_secret;
8173         let next_per_commitment_point;
8174         {
8175                 let mut guard = nodes[0].node.channel_state.lock().unwrap();
8176                 let keys = guard.by_id.get_mut(&channel_id).unwrap().get_signer();
8177
8178                 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
8179
8180                 // Make signer believe we got a counterparty signature, so that it allows the revocation
8181                 keys.get_enforcement_state().last_holder_commitment -= 1;
8182                 per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
8183
8184                 // Must revoke without gaps
8185                 keys.get_enforcement_state().last_holder_commitment -= 1;
8186                 keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
8187
8188                 keys.get_enforcement_state().last_holder_commitment -= 1;
8189                 next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
8190                         &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
8191         }
8192
8193         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
8194                 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
8195         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
8196         check_added_monitors!(nodes[1], 1);
8197         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
8198 }
8199
8200 #[test]
8201 fn test_bump_txn_sanitize_tracking_maps() {
8202         // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
8203         // verify we clean then right after expiration of ANTI_REORG_DELAY.
8204
8205         let chanmon_cfgs = create_chanmon_cfgs(2);
8206         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8207         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8208         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8209
8210         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8211         // Lock HTLC in both directions
8212         let (payment_preimage_1, _, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000);
8213         let (_, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000);
8214
8215         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
8216         assert_eq!(revoked_local_txn[0].input.len(), 1);
8217         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8218
8219         // Revoke local commitment tx
8220         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
8221
8222         // Broadcast set of revoked txn on A
8223         connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
8224         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[0], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
8225         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
8226
8227         mine_transaction(&nodes[0], &revoked_local_txn[0]);
8228         check_closed_broadcast!(nodes[0], true);
8229         check_added_monitors!(nodes[0], 1);
8230         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8231         let penalty_txn = {
8232                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8233                 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
8234                 check_spends!(node_txn[0], revoked_local_txn[0]);
8235                 check_spends!(node_txn[1], revoked_local_txn[0]);
8236                 check_spends!(node_txn[2], revoked_local_txn[0]);
8237                 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
8238                 node_txn.clear();
8239                 penalty_txn
8240         };
8241         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8242         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
8243         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8244         {
8245                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
8246                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
8247                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
8248         }
8249 }
8250
8251 #[test]
8252 fn test_pending_claimed_htlc_no_balance_underflow() {
8253         // Tests that if we have a pending outbound HTLC as well as a claimed-but-not-fully-removed
8254         // HTLC we will not underflow when we call `Channel::get_balance_msat()`.
8255         let chanmon_cfgs = create_chanmon_cfgs(2);
8256         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8257         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8258         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8259         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8260
8261         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_010_000);
8262         nodes[1].node.claim_funds(payment_preimage);
8263         expect_payment_claimed!(nodes[1], payment_hash, 1_010_000);
8264         check_added_monitors!(nodes[1], 1);
8265         let fulfill_ev = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8266
8267         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &fulfill_ev.update_fulfill_htlcs[0]);
8268         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
8269         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &fulfill_ev.commitment_signed);
8270         check_added_monitors!(nodes[0], 1);
8271         let (_raa, _cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
8272
8273         // At this point nodes[1] has received 1,010k msat (10k msat more than their reserve) and can
8274         // send an HTLC back (though it will go in the holding cell). Send an HTLC back and check we
8275         // can get our balance.
8276
8277         // Get a route from nodes[1] to nodes[0] by getting a route going the other way and then flip
8278         // the public key of the only hop. This works around ChannelDetails not showing the
8279         // almost-claimed HTLC as available balance.
8280         let (mut route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 10_000);
8281         route.payment_params = None; // This is all wrong, but unnecessary
8282         route.paths[0][0].pubkey = nodes[0].node.get_our_node_id();
8283         let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[0]);
8284         nodes[1].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
8285
8286         assert_eq!(nodes[1].node.list_channels()[0].balance_msat, 1_000_000);
8287 }
8288
8289 #[test]
8290 fn test_channel_conf_timeout() {
8291         // Tests that, for inbound channels, we give up on them if the funding transaction does not
8292         // confirm within 2016 blocks, as recommended by BOLT 2.
8293         let chanmon_cfgs = create_chanmon_cfgs(2);
8294         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8295         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8296         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8297
8298         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());
8299
8300         // The outbound node should wait forever for confirmation:
8301         // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
8302         // copied here instead of directly referencing the constant.
8303         connect_blocks(&nodes[0], 2016);
8304         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8305
8306         // The inbound node should fail the channel after exactly 2016 blocks
8307         connect_blocks(&nodes[1], 2015);
8308         check_added_monitors!(nodes[1], 0);
8309         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8310
8311         connect_blocks(&nodes[1], 1);
8312         check_added_monitors!(nodes[1], 1);
8313         check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut);
8314         let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
8315         assert_eq!(close_ev.len(), 1);
8316         match close_ev[0] {
8317                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
8318                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8319                         assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
8320                 },
8321                 _ => panic!("Unexpected event"),
8322         }
8323 }
8324
8325 #[test]
8326 fn test_override_channel_config() {
8327         let chanmon_cfgs = create_chanmon_cfgs(2);
8328         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8329         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8330         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8331
8332         // Node0 initiates a channel to node1 using the override config.
8333         let mut override_config = UserConfig::default();
8334         override_config.channel_handshake_config.our_to_self_delay = 200;
8335
8336         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
8337
8338         // Assert the channel created by node0 is using the override config.
8339         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8340         assert_eq!(res.channel_flags, 0);
8341         assert_eq!(res.to_self_delay, 200);
8342 }
8343
8344 #[test]
8345 fn test_override_0msat_htlc_minimum() {
8346         let mut zero_config = UserConfig::default();
8347         zero_config.channel_handshake_config.our_htlc_minimum_msat = 0;
8348         let chanmon_cfgs = create_chanmon_cfgs(2);
8349         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8350         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
8351         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8352
8353         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
8354         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8355         assert_eq!(res.htlc_minimum_msat, 1);
8356
8357         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &res);
8358         let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8359         assert_eq!(res.htlc_minimum_msat, 1);
8360 }
8361
8362 #[test]
8363 fn test_channel_update_has_correct_htlc_maximum_msat() {
8364         // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
8365         // Bolt 7 specifies that if present `htlc_maximum_msat`:
8366         // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
8367         // 90% of the `channel_value`.
8368         // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
8369
8370         let mut config_30_percent = UserConfig::default();
8371         config_30_percent.channel_handshake_config.announced_channel = true;
8372         config_30_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
8373         let mut config_50_percent = UserConfig::default();
8374         config_50_percent.channel_handshake_config.announced_channel = true;
8375         config_50_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
8376         let mut config_95_percent = UserConfig::default();
8377         config_95_percent.channel_handshake_config.announced_channel = true;
8378         config_95_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
8379         let mut config_100_percent = UserConfig::default();
8380         config_100_percent.channel_handshake_config.announced_channel = true;
8381         config_100_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
8382
8383         let chanmon_cfgs = create_chanmon_cfgs(4);
8384         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8385         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)]);
8386         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8387
8388         let channel_value_satoshis = 100000;
8389         let channel_value_msat = channel_value_satoshis * 1000;
8390         let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
8391         let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
8392         let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
8393
8394         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());
8395         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());
8396
8397         // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
8398         // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
8399         assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, channel_value_50_percent_msat);
8400         // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
8401         // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
8402         assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, channel_value_30_percent_msat);
8403
8404         // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
8405         // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
8406         // `channel_value`.
8407         assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
8408         // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
8409         // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
8410         // `channel_value`.
8411         assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
8412 }
8413
8414 #[test]
8415 fn test_manually_accept_inbound_channel_request() {
8416         let mut manually_accept_conf = UserConfig::default();
8417         manually_accept_conf.manually_accept_inbound_channels = true;
8418         let chanmon_cfgs = create_chanmon_cfgs(2);
8419         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8420         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8421         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8422
8423         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8424         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8425
8426         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &res);
8427
8428         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8429         // accepting the inbound channel request.
8430         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8431
8432         let events = nodes[1].node.get_and_clear_pending_events();
8433         match events[0] {
8434                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8435                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
8436                 }
8437                 _ => panic!("Unexpected event"),
8438         }
8439
8440         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8441         assert_eq!(accept_msg_ev.len(), 1);
8442
8443         match accept_msg_ev[0] {
8444                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8445                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8446                 }
8447                 _ => panic!("Unexpected event"),
8448         }
8449
8450         nodes[1].node.force_close_broadcasting_latest_txn(&temp_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
8451
8452         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8453         assert_eq!(close_msg_ev.len(), 1);
8454
8455         let events = nodes[1].node.get_and_clear_pending_events();
8456         match events[0] {
8457                 Event::ChannelClosed { user_channel_id, .. } => {
8458                         assert_eq!(user_channel_id, 23);
8459                 }
8460                 _ => panic!("Unexpected event"),
8461         }
8462 }
8463
8464 #[test]
8465 fn test_manually_reject_inbound_channel_request() {
8466         let mut manually_accept_conf = UserConfig::default();
8467         manually_accept_conf.manually_accept_inbound_channels = true;
8468         let chanmon_cfgs = create_chanmon_cfgs(2);
8469         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8470         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8471         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8472
8473         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8474         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8475
8476         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &res);
8477
8478         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8479         // rejecting the inbound channel request.
8480         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8481
8482         let events = nodes[1].node.get_and_clear_pending_events();
8483         match events[0] {
8484                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8485                         nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
8486                 }
8487                 _ => panic!("Unexpected event"),
8488         }
8489
8490         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8491         assert_eq!(close_msg_ev.len(), 1);
8492
8493         match close_msg_ev[0] {
8494                 MessageSendEvent::HandleError { ref node_id, .. } => {
8495                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8496                 }
8497                 _ => panic!("Unexpected event"),
8498         }
8499         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
8500 }
8501
8502 #[test]
8503 fn test_reject_funding_before_inbound_channel_accepted() {
8504         // This tests that when `UserConfig::manually_accept_inbound_channels` is set to true, inbound
8505         // channels must to be manually accepted through `ChannelManager::accept_inbound_channel` by
8506         // the node operator before the counterparty sends a `FundingCreated` message. If a
8507         // `FundingCreated` message is received before the channel is accepted, it should be rejected
8508         // and the channel should be closed.
8509         let mut manually_accept_conf = UserConfig::default();
8510         manually_accept_conf.manually_accept_inbound_channels = true;
8511         let chanmon_cfgs = create_chanmon_cfgs(2);
8512         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8513         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8514         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8515
8516         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8517         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8518         let temp_channel_id = res.temporary_channel_id;
8519
8520         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &res);
8521
8522         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in the `msg_events`.
8523         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8524
8525         // Clear the `Event::OpenChannelRequest` event without responding to the request.
8526         nodes[1].node.get_and_clear_pending_events();
8527
8528         // Get the `AcceptChannel` message of `nodes[1]` without calling
8529         // `ChannelManager::accept_inbound_channel`, which generates a
8530         // `MessageSendEvent::SendAcceptChannel` event. The message is passed to `nodes[0]`
8531         // `handle_accept_channel`, which is required in order for `create_funding_transaction` to
8532         // succeed when `nodes[0]` is passed to it.
8533         let accept_chan_msg = {
8534                 let mut lock;
8535                 let channel = get_channel_ref!(&nodes[1], lock, temp_channel_id);
8536                 channel.get_accept_channel_message()
8537         };
8538         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_chan_msg);
8539
8540         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8541
8542         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8543         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8544
8545         // The `funding_created_msg` should be rejected by `nodes[1]` as it hasn't accepted the channel
8546         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8547
8548         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8549         assert_eq!(close_msg_ev.len(), 1);
8550
8551         let expected_err = "FundingCreated message received before the channel was accepted";
8552         match close_msg_ev[0] {
8553                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id, } => {
8554                         assert_eq!(msg.channel_id, temp_channel_id);
8555                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8556                         assert_eq!(msg.data, expected_err);
8557                 }
8558                 _ => panic!("Unexpected event"),
8559         }
8560
8561         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
8562 }
8563
8564 #[test]
8565 fn test_can_not_accept_inbound_channel_twice() {
8566         let mut manually_accept_conf = UserConfig::default();
8567         manually_accept_conf.manually_accept_inbound_channels = true;
8568         let chanmon_cfgs = create_chanmon_cfgs(2);
8569         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8570         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8571         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8572
8573         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8574         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8575
8576         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &res);
8577
8578         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8579         // accepting the inbound channel request.
8580         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8581
8582         let events = nodes[1].node.get_and_clear_pending_events();
8583         match events[0] {
8584                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8585                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
8586                         let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
8587                         match api_res {
8588                                 Err(APIError::APIMisuseError { err }) => {
8589                                         assert_eq!(err, "The channel isn't currently awaiting to be accepted.");
8590                                 },
8591                                 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
8592                                 Err(_) => panic!("Unexpected Error"),
8593                         }
8594                 }
8595                 _ => panic!("Unexpected event"),
8596         }
8597
8598         // Ensure that the channel wasn't closed after attempting to accept it twice.
8599         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8600         assert_eq!(accept_msg_ev.len(), 1);
8601
8602         match accept_msg_ev[0] {
8603                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8604                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8605                 }
8606                 _ => panic!("Unexpected event"),
8607         }
8608 }
8609
8610 #[test]
8611 fn test_can_not_accept_unknown_inbound_channel() {
8612         let chanmon_cfg = create_chanmon_cfgs(2);
8613         let node_cfg = create_node_cfgs(2, &chanmon_cfg);
8614         let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
8615         let nodes = create_network(2, &node_cfg, &node_chanmgr);
8616
8617         let unknown_channel_id = [0; 32];
8618         let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
8619         match api_res {
8620                 Err(APIError::ChannelUnavailable { err }) => {
8621                         assert_eq!(err, "Can't accept a channel that doesn't exist");
8622                 },
8623                 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
8624                 Err(_) => panic!("Unexpected Error"),
8625         }
8626 }
8627
8628 #[test]
8629 fn test_simple_mpp() {
8630         // Simple test of sending a multi-path payment.
8631         let chanmon_cfgs = create_chanmon_cfgs(4);
8632         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8633         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8634         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8635
8636         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;
8637         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;
8638         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;
8639         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;
8640
8641         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8642         let path = route.paths[0].clone();
8643         route.paths.push(path);
8644         route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8645         route.paths[0][0].short_channel_id = chan_1_id;
8646         route.paths[0][1].short_channel_id = chan_3_id;
8647         route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8648         route.paths[1][0].short_channel_id = chan_2_id;
8649         route.paths[1][1].short_channel_id = chan_4_id;
8650         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8651         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8652 }
8653
8654 #[test]
8655 fn test_preimage_storage() {
8656         // Simple test of payment preimage storage allowing no client-side storage to claim payments
8657         let chanmon_cfgs = create_chanmon_cfgs(2);
8658         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8659         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8660         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8661
8662         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).0.contents.short_channel_id;
8663
8664         {
8665                 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200).unwrap();
8666                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8667                 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
8668                 check_added_monitors!(nodes[0], 1);
8669                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8670                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8671                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8672                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8673         }
8674         // Note that after leaving the above scope we have no knowledge of any arguments or return
8675         // values from previous calls.
8676         expect_pending_htlcs_forwardable!(nodes[1]);
8677         let events = nodes[1].node.get_and_clear_pending_events();
8678         assert_eq!(events.len(), 1);
8679         match events[0] {
8680                 Event::PaymentReceived { ref purpose, .. } => {
8681                         match &purpose {
8682                                 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
8683                                         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8684                                 },
8685                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
8686                         }
8687                 },
8688                 _ => panic!("Unexpected event"),
8689         }
8690 }
8691
8692 #[test]
8693 #[allow(deprecated)]
8694 fn test_secret_timeout() {
8695         // Simple test of payment secret storage time outs. After
8696         // `create_inbound_payment(_for_hash)_legacy` is removed, this test will be removed as well.
8697         let chanmon_cfgs = create_chanmon_cfgs(2);
8698         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8699         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8700         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8701
8702         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).0.contents.short_channel_id;
8703
8704         let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment_legacy(Some(100_000), 2).unwrap();
8705
8706         // We should fail to register the same payment hash twice, at least until we've connected a
8707         // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
8708         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8709                 assert_eq!(err, "Duplicate payment hash");
8710         } else { panic!(); }
8711         let mut block = {
8712                 let node_1_blocks = nodes[1].blocks.lock().unwrap();
8713                 Block {
8714                         header: BlockHeader {
8715                                 version: 0x2000000,
8716                                 prev_blockhash: node_1_blocks.last().unwrap().0.block_hash(),
8717                                 merkle_root: TxMerkleNode::all_zeros(),
8718                                 time: node_1_blocks.len() as u32 + 7200, bits: 42, nonce: 42 },
8719                         txdata: vec![],
8720                 }
8721         };
8722         connect_block(&nodes[1], &block);
8723         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8724                 assert_eq!(err, "Duplicate payment hash");
8725         } else { panic!(); }
8726
8727         // If we then connect the second block, we should be able to register the same payment hash
8728         // again (this time getting a new payment secret).
8729         block.header.prev_blockhash = block.header.block_hash();
8730         block.header.time += 1;
8731         connect_block(&nodes[1], &block);
8732         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2).unwrap();
8733         assert_ne!(payment_secret_1, our_payment_secret);
8734
8735         {
8736                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8737                 nodes[0].node.send_payment(&route, payment_hash, &Some(our_payment_secret), PaymentId(payment_hash.0)).unwrap();
8738                 check_added_monitors!(nodes[0], 1);
8739                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8740                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8741                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8742                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8743         }
8744         // Note that after leaving the above scope we have no knowledge of any arguments or return
8745         // values from previous calls.
8746         expect_pending_htlcs_forwardable!(nodes[1]);
8747         let events = nodes[1].node.get_and_clear_pending_events();
8748         assert_eq!(events.len(), 1);
8749         match events[0] {
8750                 Event::PaymentReceived { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret }, .. } => {
8751                         assert!(payment_preimage.is_none());
8752                         assert_eq!(payment_secret, our_payment_secret);
8753                         // We don't actually have the payment preimage with which to claim this payment!
8754                 },
8755                 _ => panic!("Unexpected event"),
8756         }
8757 }
8758
8759 #[test]
8760 fn test_bad_secret_hash() {
8761         // Simple test of unregistered payment hash/invalid payment secret handling
8762         let chanmon_cfgs = create_chanmon_cfgs(2);
8763         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8764         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8765         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8766
8767         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).0.contents.short_channel_id;
8768
8769         let random_payment_hash = PaymentHash([42; 32]);
8770         let random_payment_secret = PaymentSecret([43; 32]);
8771         let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2).unwrap();
8772         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8773
8774         // All the below cases should end up being handled exactly identically, so we macro the
8775         // resulting events.
8776         macro_rules! handle_unknown_invalid_payment_data {
8777                 ($payment_hash: expr) => {
8778                         check_added_monitors!(nodes[0], 1);
8779                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8780                         let payment_event = SendEvent::from_event(events.pop().unwrap());
8781                         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8782                         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8783
8784                         // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8785                         // again to process the pending backwards-failure of the HTLC
8786                         expect_pending_htlcs_forwardable!(nodes[1]);
8787                         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment{ payment_hash: $payment_hash }]);
8788                         check_added_monitors!(nodes[1], 1);
8789
8790                         // We should fail the payment back
8791                         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8792                         match events.pop().unwrap() {
8793                                 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8794                                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8795                                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8796                                 },
8797                                 _ => panic!("Unexpected event"),
8798                         }
8799                 }
8800         }
8801
8802         let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8803         // Error data is the HTLC value (100,000) and current block height
8804         let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8805
8806         // Send a payment with the right payment hash but the wrong payment secret
8807         nodes[0].node.send_payment(&route, our_payment_hash, &Some(random_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
8808         handle_unknown_invalid_payment_data!(our_payment_hash);
8809         expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8810
8811         // Send a payment with a random payment hash, but the right payment secret
8812         nodes[0].node.send_payment(&route, random_payment_hash, &Some(our_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8813         handle_unknown_invalid_payment_data!(random_payment_hash);
8814         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8815
8816         // Send a payment with a random payment hash and random payment secret
8817         nodes[0].node.send_payment(&route, random_payment_hash, &Some(random_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8818         handle_unknown_invalid_payment_data!(random_payment_hash);
8819         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8820 }
8821
8822 #[test]
8823 fn test_update_err_monitor_lockdown() {
8824         // Our monitor will lock update of local commitment transaction if a broadcastion condition
8825         // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8826         // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateStatus
8827         // error.
8828         //
8829         // This scenario may happen in a watchtower setup, where watchtower process a block height
8830         // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8831         // commitment at same time.
8832
8833         let chanmon_cfgs = create_chanmon_cfgs(2);
8834         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8835         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8836         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8837
8838         // Create some initial channel
8839         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8840         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8841
8842         // Rebalance the network to generate htlc in the two directions
8843         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8844
8845         // Route a HTLC from node 0 to node 1 (but don't settle)
8846         let (preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
8847
8848         // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8849         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8850         let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8851         let persister = test_utils::TestPersister::new();
8852         let watchtower = {
8853                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8854                 let mut w = test_utils::TestVecWriter(Vec::new());
8855                 monitor.write(&mut w).unwrap();
8856                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8857                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8858                 assert!(new_monitor == *monitor);
8859                 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);
8860                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8861                 watchtower
8862         };
8863         let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8864         let block = Block { header, txdata: vec![] };
8865         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8866         // transaction lock time requirements here.
8867         chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 0));
8868         watchtower.chain_monitor.block_connected(&block, 200);
8869
8870         // Try to update ChannelMonitor
8871         nodes[1].node.claim_funds(preimage);
8872         check_added_monitors!(nodes[1], 1);
8873         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
8874
8875         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8876         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8877         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8878         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8879                 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8880                         assert_eq!(watchtower.chain_monitor.update_channel(outpoint, update.clone()), ChannelMonitorUpdateStatus::PermanentFailure);
8881                         assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, update), ChannelMonitorUpdateStatus::Completed);
8882                 } else { assert!(false); }
8883         } else { assert!(false); };
8884         // Our local monitor is in-sync and hasn't processed yet timeout
8885         check_added_monitors!(nodes[0], 1);
8886         let events = nodes[0].node.get_and_clear_pending_events();
8887         assert_eq!(events.len(), 1);
8888 }
8889
8890 #[test]
8891 fn test_concurrent_monitor_claim() {
8892         // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8893         // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8894         // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8895         // state N+1 confirms. Alice claims output from state N+1.
8896
8897         let chanmon_cfgs = create_chanmon_cfgs(2);
8898         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8899         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8900         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8901
8902         // Create some initial channel
8903         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8904         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8905
8906         // Rebalance the network to generate htlc in the two directions
8907         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8908
8909         // Route a HTLC from node 0 to node 1 (but don't settle)
8910         route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8911
8912         // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8913         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8914         let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8915         let persister = test_utils::TestPersister::new();
8916         let watchtower_alice = {
8917                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8918                 let mut w = test_utils::TestVecWriter(Vec::new());
8919                 monitor.write(&mut w).unwrap();
8920                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8921                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8922                 assert!(new_monitor == *monitor);
8923                 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);
8924                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8925                 watchtower
8926         };
8927         let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8928         let block = Block { header, txdata: vec![] };
8929         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8930         // transaction lock time requirements here.
8931         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));
8932         watchtower_alice.chain_monitor.block_connected(&block, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8933
8934         // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8935         {
8936                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8937                 assert_eq!(txn.len(), 2);
8938                 txn.clear();
8939         }
8940
8941         // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8942         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8943         let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8944         let persister = test_utils::TestPersister::new();
8945         let watchtower_bob = {
8946                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8947                 let mut w = test_utils::TestVecWriter(Vec::new());
8948                 monitor.write(&mut w).unwrap();
8949                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8950                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8951                 assert!(new_monitor == *monitor);
8952                 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);
8953                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8954                 watchtower
8955         };
8956         let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8957         watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8958
8959         // Route another payment to generate another update with still previous HTLC pending
8960         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8961         {
8962                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
8963         }
8964         check_added_monitors!(nodes[1], 1);
8965
8966         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8967         assert_eq!(updates.update_add_htlcs.len(), 1);
8968         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8969         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8970                 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8971                         // Watchtower Alice should already have seen the block and reject the update
8972                         assert_eq!(watchtower_alice.chain_monitor.update_channel(outpoint, update.clone()), ChannelMonitorUpdateStatus::PermanentFailure);
8973                         assert_eq!(watchtower_bob.chain_monitor.update_channel(outpoint, update.clone()), ChannelMonitorUpdateStatus::Completed);
8974                         assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, update), ChannelMonitorUpdateStatus::Completed);
8975                 } else { assert!(false); }
8976         } else { assert!(false); };
8977         // Our local monitor is in-sync and hasn't processed yet timeout
8978         check_added_monitors!(nodes[0], 1);
8979
8980         //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8981         let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8982         watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8983
8984         // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8985         let bob_state_y;
8986         {
8987                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8988                 assert_eq!(txn.len(), 2);
8989                 bob_state_y = txn[0].clone();
8990                 txn.clear();
8991         };
8992
8993         // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8994         let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8995         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);
8996         {
8997                 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8998                 assert_eq!(htlc_txn.len(), 1);
8999                 check_spends!(htlc_txn[0], bob_state_y);
9000         }
9001 }
9002
9003 #[test]
9004 fn test_pre_lockin_no_chan_closed_update() {
9005         // Test that if a peer closes a channel in response to a funding_created message we don't
9006         // generate a channel update (as the channel cannot appear on chain without a funding_signed
9007         // message).
9008         //
9009         // Doing so would imply a channel monitor update before the initial channel monitor
9010         // registration, violating our API guarantees.
9011         //
9012         // Previously, full_stack_target managed to hit this case by opening then closing a channel,
9013         // then opening a second channel with the same funding output as the first (which is not
9014         // rejected because the first channel does not exist in the ChannelManager) and closing it
9015         // before receiving funding_signed.
9016         let chanmon_cfgs = create_chanmon_cfgs(2);
9017         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9018         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9019         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9020
9021         // Create an initial channel
9022         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9023         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9024         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_chan_msg);
9025         let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9026         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_chan_msg);
9027
9028         // Move the first channel through the funding flow...
9029         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
9030
9031         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9032         check_added_monitors!(nodes[0], 0);
9033
9034         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9035         let channel_id = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
9036         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
9037         assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
9038         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "Hi".to_string() }, true);
9039 }
9040
9041 #[test]
9042 fn test_htlc_no_detection() {
9043         // This test is a mutation to underscore the detection logic bug we had
9044         // before #653. HTLC value routed is above the remaining balance, thus
9045         // inverting HTLC and `to_remote` output. HTLC will come second and
9046         // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
9047         // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
9048         // outputs order detection for correct spending children filtring.
9049
9050         let chanmon_cfgs = create_chanmon_cfgs(2);
9051         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9052         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9053         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9054
9055         // Create some initial channels
9056         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9057
9058         send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
9059         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
9060         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
9061         assert_eq!(local_txn[0].input.len(), 1);
9062         assert_eq!(local_txn[0].output.len(), 3);
9063         check_spends!(local_txn[0], chan_1.3);
9064
9065         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
9066         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
9067         connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] });
9068         // We deliberately connect the local tx twice as this should provoke a failure calling
9069         // this test before #653 fix.
9070         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);
9071         check_closed_broadcast!(nodes[0], true);
9072         check_added_monitors!(nodes[0], 1);
9073         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
9074         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1);
9075
9076         let htlc_timeout = {
9077                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
9078                 assert_eq!(node_txn[1].input.len(), 1);
9079                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9080                 check_spends!(node_txn[1], local_txn[0]);
9081                 node_txn[1].clone()
9082         };
9083
9084         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
9085         connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] });
9086         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
9087         expect_payment_failed!(nodes[0], our_payment_hash, false);
9088 }
9089
9090 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
9091         // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
9092         // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
9093         // Carol, Alice would be the upstream node, and Carol the downstream.)
9094         //
9095         // Steps of the test:
9096         // 1) Alice sends a HTLC to Carol through Bob.
9097         // 2) Carol doesn't settle the HTLC.
9098         // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
9099         // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
9100         // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
9101         //    but can't be claimed as Bob doesn't have yet knowledge of the preimage.
9102         // 5) Carol release the preimage to Bob off-chain.
9103         // 6) Bob claims the offered output on the broadcasted commitment.
9104         let chanmon_cfgs = create_chanmon_cfgs(3);
9105         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9106         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9107         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9108
9109         // Create some initial channels
9110         let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9111         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9112
9113         // Steps (1) and (2):
9114         // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
9115         let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
9116
9117         // Check that Alice's commitment transaction now contains an output for this HTLC.
9118         let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
9119         check_spends!(alice_txn[0], chan_ab.3);
9120         assert_eq!(alice_txn[0].output.len(), 2);
9121         check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
9122         assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9123         assert_eq!(alice_txn.len(), 2);
9124
9125         // Steps (3) and (4):
9126         // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
9127         // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
9128         let mut force_closing_node = 0; // Alice force-closes
9129         let mut counterparty_node = 1; // Bob if Alice force-closes
9130
9131         // Bob force-closes
9132         if !broadcast_alice {
9133                 force_closing_node = 1;
9134                 counterparty_node = 0;
9135         }
9136         nodes[force_closing_node].node.force_close_broadcasting_latest_txn(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id()).unwrap();
9137         check_closed_broadcast!(nodes[force_closing_node], true);
9138         check_added_monitors!(nodes[force_closing_node], 1);
9139         check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
9140         if go_onchain_before_fulfill {
9141                 let txn_to_broadcast = match broadcast_alice {
9142                         true => alice_txn.clone(),
9143                         false => get_local_commitment_txn!(nodes[1], chan_ab.2)
9144                 };
9145                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
9146                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
9147                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
9148                 if broadcast_alice {
9149                         check_closed_broadcast!(nodes[1], true);
9150                         check_added_monitors!(nodes[1], 1);
9151                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
9152                 }
9153                 assert_eq!(bob_txn.len(), 1);
9154                 check_spends!(bob_txn[0], chan_ab.3);
9155         }
9156
9157         // Step (5):
9158         // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
9159         // process of removing the HTLC from their commitment transactions.
9160         nodes[2].node.claim_funds(payment_preimage);
9161         check_added_monitors!(nodes[2], 1);
9162         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
9163
9164         let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
9165         assert!(carol_updates.update_add_htlcs.is_empty());
9166         assert!(carol_updates.update_fail_htlcs.is_empty());
9167         assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
9168         assert!(carol_updates.update_fee.is_none());
9169         assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
9170
9171         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
9172         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false, false);
9173         // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
9174         if !go_onchain_before_fulfill && broadcast_alice {
9175                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9176                 assert_eq!(events.len(), 1);
9177                 match events[0] {
9178                         MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
9179                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9180                         },
9181                         _ => panic!("Unexpected event"),
9182                 };
9183         }
9184         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
9185         // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
9186         // Carol<->Bob's updated commitment transaction info.
9187         check_added_monitors!(nodes[1], 2);
9188
9189         let events = nodes[1].node.get_and_clear_pending_msg_events();
9190         assert_eq!(events.len(), 2);
9191         let bob_revocation = match events[0] {
9192                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
9193                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
9194                         (*msg).clone()
9195                 },
9196                 _ => panic!("Unexpected event"),
9197         };
9198         let bob_updates = match events[1] {
9199                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
9200                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
9201                         (*updates).clone()
9202                 },
9203                 _ => panic!("Unexpected event"),
9204         };
9205
9206         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
9207         check_added_monitors!(nodes[2], 1);
9208         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
9209         check_added_monitors!(nodes[2], 1);
9210
9211         let events = nodes[2].node.get_and_clear_pending_msg_events();
9212         assert_eq!(events.len(), 1);
9213         let carol_revocation = match events[0] {
9214                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
9215                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
9216                         (*msg).clone()
9217                 },
9218                 _ => panic!("Unexpected event"),
9219         };
9220         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
9221         check_added_monitors!(nodes[1], 1);
9222
9223         // If this test requires the force-closed channel to not be on-chain until after the fulfill,
9224         // here's where we put said channel's commitment tx on-chain.
9225         let mut txn_to_broadcast = alice_txn.clone();
9226         if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
9227         if !go_onchain_before_fulfill {
9228                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
9229                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
9230                 // If Bob was the one to force-close, he will have already passed these checks earlier.
9231                 if broadcast_alice {
9232                         check_closed_broadcast!(nodes[1], true);
9233                         check_added_monitors!(nodes[1], 1);
9234                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
9235                 }
9236                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9237                 if broadcast_alice {
9238                         // In `connect_block()`, the ChainMonitor and ChannelManager are separately notified about a
9239                         // new block being connected. The ChannelManager being notified triggers a monitor update,
9240                         // which triggers broadcasting our commitment tx and an HTLC-claiming tx. The ChainMonitor
9241                         // being notified triggers the HTLC-claiming tx redundantly, resulting in 3 total txs being
9242                         // broadcasted.
9243                         assert_eq!(bob_txn.len(), 3);
9244                         check_spends!(bob_txn[1], chan_ab.3);
9245                 } else {
9246                         assert_eq!(bob_txn.len(), 2);
9247                         check_spends!(bob_txn[0], chan_ab.3);
9248                 }
9249         }
9250
9251         // Step (6):
9252         // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
9253         // broadcasted commitment transaction.
9254         {
9255                 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
9256                 if go_onchain_before_fulfill {
9257                         // Bob should now have an extra broadcasted tx, for the preimage-claiming transaction.
9258                         assert_eq!(bob_txn.len(), 2);
9259                 }
9260                 let script_weight = match broadcast_alice {
9261                         true => OFFERED_HTLC_SCRIPT_WEIGHT,
9262                         false => ACCEPTED_HTLC_SCRIPT_WEIGHT
9263                 };
9264                 // If Alice force-closed and Bob didn't receive her commitment transaction until after he
9265                 // received Carol's fulfill, he broadcasts the HTLC-output-claiming transaction first. Else if
9266                 // Bob force closed or if he found out about Alice's commitment tx before receiving Carol's
9267                 // fulfill, then he broadcasts the HTLC-output-claiming transaction second.
9268                 if broadcast_alice && !go_onchain_before_fulfill {
9269                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
9270                         assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
9271                 } else {
9272                         check_spends!(bob_txn[1], txn_to_broadcast[0]);
9273                         assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
9274                 }
9275         }
9276 }
9277
9278 #[test]
9279 fn test_onchain_htlc_settlement_after_close() {
9280         do_test_onchain_htlc_settlement_after_close(true, true);
9281         do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
9282         do_test_onchain_htlc_settlement_after_close(true, false);
9283         do_test_onchain_htlc_settlement_after_close(false, false);
9284 }
9285
9286 #[test]
9287 fn test_duplicate_chan_id() {
9288         // Test that if a given peer tries to open a channel with the same channel_id as one that is
9289         // already open we reject it and keep the old channel.
9290         //
9291         // Previously, full_stack_target managed to figure out that if you tried to open two channels
9292         // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
9293         // the existing channel when we detect the duplicate new channel, screwing up our monitor
9294         // updating logic for the existing channel.
9295         let chanmon_cfgs = create_chanmon_cfgs(2);
9296         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9297         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9298         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9299
9300         // Create an initial channel
9301         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9302         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9303         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_chan_msg);
9304         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()));
9305
9306         // Try to create a second channel with the same temporary_channel_id as the first and check
9307         // that it is rejected.
9308         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_chan_msg);
9309         {
9310                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9311                 assert_eq!(events.len(), 1);
9312                 match events[0] {
9313                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9314                                 // Technically, at this point, nodes[1] would be justified in thinking both the
9315                                 // first (valid) and second (invalid) channels are closed, given they both have
9316                                 // the same non-temporary channel_id. However, currently we do not, so we just
9317                                 // move forward with it.
9318                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9319                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9320                         },
9321                         _ => panic!("Unexpected event"),
9322                 }
9323         }
9324
9325         // Move the first channel through the funding flow...
9326         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
9327
9328         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9329         check_added_monitors!(nodes[0], 0);
9330
9331         let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9332         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
9333         {
9334                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
9335                 assert_eq!(added_monitors.len(), 1);
9336                 assert_eq!(added_monitors[0].0, funding_output);
9337                 added_monitors.clear();
9338         }
9339         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9340
9341         let funding_outpoint = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
9342         let channel_id = funding_outpoint.to_channel_id();
9343
9344         // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
9345         // temporary one).
9346
9347         // First try to open a second channel with a temporary channel id equal to the txid-based one.
9348         // Technically this is allowed by the spec, but we don't support it and there's little reason
9349         // to. Still, it shouldn't cause any other issues.
9350         open_chan_msg.temporary_channel_id = channel_id;
9351         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_chan_msg);
9352         {
9353                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9354                 assert_eq!(events.len(), 1);
9355                 match events[0] {
9356                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9357                                 // Technically, at this point, nodes[1] would be justified in thinking both
9358                                 // channels are closed, but currently we do not, so we just move forward with it.
9359                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9360                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9361                         },
9362                         _ => panic!("Unexpected event"),
9363                 }
9364         }
9365
9366         // Now try to create a second channel which has a duplicate funding output.
9367         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9368         let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9369         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_chan_2_msg);
9370         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()));
9371         create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
9372
9373         let funding_created = {
9374                 let mut a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
9375                 // Once we call `get_outbound_funding_created` the channel has a duplicate channel_id as
9376                 // another channel in the ChannelManager - an invalid state. Thus, we'd panic later when we
9377                 // try to create another channel. Instead, we drop the channel entirely here (leaving the
9378                 // channelmanager in a possibly nonsense state instead).
9379                 let mut as_chan = a_channel_lock.by_id.remove(&open_chan_2_msg.temporary_channel_id).unwrap();
9380                 let logger = test_utils::TestLogger::new();
9381                 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
9382         };
9383         check_added_monitors!(nodes[0], 0);
9384         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
9385         // At this point we'll try to add a duplicate channel monitor, which will be rejected, but
9386         // still needs to be cleared here.
9387         check_added_monitors!(nodes[1], 1);
9388
9389         // ...still, nodes[1] will reject the duplicate channel.
9390         {
9391                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9392                 assert_eq!(events.len(), 1);
9393                 match events[0] {
9394                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9395                                 // Technically, at this point, nodes[1] would be justified in thinking both
9396                                 // channels are closed, but currently we do not, so we just move forward with it.
9397                                 assert_eq!(msg.channel_id, channel_id);
9398                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9399                         },
9400                         _ => panic!("Unexpected event"),
9401                 }
9402         }
9403
9404         // finally, finish creating the original channel and send a payment over it to make sure
9405         // everything is functional.
9406         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
9407         {
9408                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9409                 assert_eq!(added_monitors.len(), 1);
9410                 assert_eq!(added_monitors[0].0, funding_output);
9411                 added_monitors.clear();
9412         }
9413
9414         let events_4 = nodes[0].node.get_and_clear_pending_events();
9415         assert_eq!(events_4.len(), 0);
9416         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9417         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9418
9419         let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9420         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9421         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9422         send_payment(&nodes[0], &[&nodes[1]], 8000000);
9423 }
9424
9425 #[test]
9426 fn test_error_chans_closed() {
9427         // Test that we properly handle error messages, closing appropriate channels.
9428         //
9429         // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
9430         // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
9431         // we can test various edge cases around it to ensure we don't regress.
9432         let chanmon_cfgs = create_chanmon_cfgs(3);
9433         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9434         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9435         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9436
9437         // Create some initial channels
9438         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9439         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9440         let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9441
9442         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9443         assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
9444         assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
9445
9446         // Closing a channel from a different peer has no effect
9447         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
9448         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9449
9450         // Closing one channel doesn't impact others
9451         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
9452         check_added_monitors!(nodes[0], 1);
9453         check_closed_broadcast!(nodes[0], false);
9454         check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
9455         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
9456         assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
9457         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);
9458         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);
9459
9460         // A null channel ID should close all channels
9461         let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9462         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
9463         check_added_monitors!(nodes[0], 2);
9464         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
9465         let events = nodes[0].node.get_and_clear_pending_msg_events();
9466         assert_eq!(events.len(), 2);
9467         match events[0] {
9468                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9469                         assert_eq!(msg.contents.flags & 2, 2);
9470                 },
9471                 _ => panic!("Unexpected event"),
9472         }
9473         match events[1] {
9474                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9475                         assert_eq!(msg.contents.flags & 2, 2);
9476                 },
9477                 _ => panic!("Unexpected event"),
9478         }
9479         // Note that at this point users of a standard PeerHandler will end up calling
9480         // peer_disconnected with no_connection_possible set to false, duplicating the
9481         // close-all-channels logic. That's OK, we don't want to end up not force-closing channels for
9482         // users with their own peer handling logic. We duplicate the call here, however.
9483         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9484         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9485
9486         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
9487         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9488         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9489 }
9490
9491 #[test]
9492 fn test_invalid_funding_tx() {
9493         // Test that we properly handle invalid funding transactions sent to us from a peer.
9494         //
9495         // Previously, all other major lightning implementations had failed to properly sanitize
9496         // funding transactions from their counterparties, leading to a multi-implementation critical
9497         // security vulnerability (though we always sanitized properly, we've previously had
9498         // un-released crashes in the sanitization process).
9499         //
9500         // Further, if the funding transaction is consensus-valid, confirms, and is later spent, we'd
9501         // previously have crashed in `ChannelMonitor` even though we closed the channel as bogus and
9502         // gave up on it. We test this here by generating such a transaction.
9503         let chanmon_cfgs = create_chanmon_cfgs(2);
9504         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9505         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9506         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9507
9508         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
9509         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()));
9510         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()));
9511
9512         let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
9513
9514         // Create a witness program which can be spent by a 4-empty-stack-elements witness and which is
9515         // 136 bytes long. This matches our "accepted HTLC preimage spend" matching, previously causing
9516         // a panic as we'd try to extract a 32 byte preimage from a witness element without checking
9517         // its length.
9518         let mut wit_program: Vec<u8> = channelmonitor::deliberately_bogus_accepted_htlc_witness_program();
9519         let wit_program_script: Script = wit_program.into();
9520         for output in tx.output.iter_mut() {
9521                 // Make the confirmed funding transaction have a bogus script_pubkey
9522                 output.script_pubkey = Script::new_v0_p2wsh(&wit_program_script.wscript_hash());
9523         }
9524
9525         nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
9526         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()));
9527         check_added_monitors!(nodes[1], 1);
9528
9529         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()));
9530         check_added_monitors!(nodes[0], 1);
9531
9532         let events_1 = nodes[0].node.get_and_clear_pending_events();
9533         assert_eq!(events_1.len(), 0);
9534
9535         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9536         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9537         nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9538
9539         let expected_err = "funding tx had wrong script/value or output index";
9540         confirm_transaction_at(&nodes[1], &tx, 1);
9541         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
9542         check_added_monitors!(nodes[1], 1);
9543         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9544         assert_eq!(events_2.len(), 1);
9545         if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9546                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9547                 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
9548                         assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
9549                 } else { panic!(); }
9550         } else { panic!(); }
9551         assert_eq!(nodes[1].node.list_channels().len(), 0);
9552
9553         // Now confirm a spend of the (bogus) funding transaction. As long as the witness is 5 elements
9554         // long the ChannelMonitor will try to read 32 bytes from the second-to-last element, panicing
9555         // as its not 32 bytes long.
9556         let mut spend_tx = Transaction {
9557                 version: 2i32, lock_time: PackedLockTime::ZERO,
9558                 input: tx.output.iter().enumerate().map(|(idx, _)| TxIn {
9559                         previous_output: BitcoinOutPoint {
9560                                 txid: tx.txid(),
9561                                 vout: idx as u32,
9562                         },
9563                         script_sig: Script::new(),
9564                         sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
9565                         witness: Witness::from_vec(channelmonitor::deliberately_bogus_accepted_htlc_witness())
9566                 }).collect(),
9567                 output: vec![TxOut {
9568                         value: 1000,
9569                         script_pubkey: Script::new(),
9570                 }]
9571         };
9572         check_spends!(spend_tx, tx);
9573         mine_transaction(&nodes[1], &spend_tx);
9574 }
9575
9576 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9577         // In the first version of the chain::Confirm interface, after a refactor was made to not
9578         // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9579         // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9580         // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9581         // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9582         // spending transaction until height N+1 (or greater). This was due to the way
9583         // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9584         // spending transaction at the height the input transaction was confirmed at, not whether we
9585         // should broadcast a spending transaction at the current height.
9586         // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9587         // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9588         // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9589         // until we learned about an additional block.
9590         //
9591         // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9592         // aren't broadcasting transactions too early (ie not broadcasting them at all).
9593         let chanmon_cfgs = create_chanmon_cfgs(3);
9594         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9595         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9596         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9597         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9598
9599         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9600         let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9601         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9602         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
9603         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9604
9605         nodes[1].node.force_close_broadcasting_latest_txn(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
9606         check_closed_broadcast!(nodes[1], true);
9607         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
9608         check_added_monitors!(nodes[1], 1);
9609         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9610         assert_eq!(node_txn.len(), 1);
9611
9612         let conf_height = nodes[1].best_block_info().1;
9613         if !test_height_before_timelock {
9614                 connect_blocks(&nodes[1], 24 * 6);
9615         }
9616         nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9617                 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9618         if test_height_before_timelock {
9619                 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9620                 // generate any events or broadcast any transactions
9621                 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9622                 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9623         } else {
9624                 // We should broadcast an HTLC transaction spending our funding transaction first
9625                 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9626                 assert_eq!(spending_txn.len(), 2);
9627                 assert_eq!(spending_txn[0], node_txn[0]);
9628                 check_spends!(spending_txn[1], node_txn[0]);
9629                 // We should also generate a SpendableOutputs event with the to_self output (as its
9630                 // timelock is up).
9631                 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9632                 assert_eq!(descriptor_spend_txn.len(), 1);
9633
9634                 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9635                 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9636                 // additional block built on top of the current chain.
9637                 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9638                         &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9639                 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 }]);
9640                 check_added_monitors!(nodes[1], 1);
9641
9642                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9643                 assert!(updates.update_add_htlcs.is_empty());
9644                 assert!(updates.update_fulfill_htlcs.is_empty());
9645                 assert_eq!(updates.update_fail_htlcs.len(), 1);
9646                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9647                 assert!(updates.update_fee.is_none());
9648                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9649                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9650                 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9651         }
9652 }
9653
9654 #[test]
9655 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9656         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9657         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9658 }
9659
9660 #[test]
9661 fn test_forwardable_regen() {
9662         // Tests that if we reload a ChannelManager while forwards are pending we will regenerate the
9663         // PendingHTLCsForwardable event automatically, ensuring we don't forget to forward/receive
9664         // HTLCs.
9665         // We test it for both payment receipt and payment forwarding.
9666
9667         let chanmon_cfgs = create_chanmon_cfgs(3);
9668         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9669         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9670         let persister: test_utils::TestPersister;
9671         let new_chain_monitor: test_utils::TestChainMonitor;
9672         let nodes_1_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
9673         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9674         let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
9675         let chan_id_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
9676
9677         // First send a payment to nodes[1]
9678         let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
9679         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
9680         check_added_monitors!(nodes[0], 1);
9681
9682         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9683         assert_eq!(events.len(), 1);
9684         let payment_event = SendEvent::from_event(events.pop().unwrap());
9685         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9686         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9687
9688         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9689
9690         // Next send a payment which is forwarded by nodes[1]
9691         let (route_2, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 200_000);
9692         nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
9693         check_added_monitors!(nodes[0], 1);
9694
9695         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9696         assert_eq!(events.len(), 1);
9697         let payment_event = SendEvent::from_event(events.pop().unwrap());
9698         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9699         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9700
9701         // There is already a PendingHTLCsForwardable event "pending" so another one will not be
9702         // generated
9703         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
9704
9705         // Now restart nodes[1] and make sure it regenerates a single PendingHTLCsForwardable
9706         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9707         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9708
9709         let nodes_1_serialized = nodes[1].node.encode();
9710         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9711         let mut chan_1_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9712         get_monitor!(nodes[1], chan_id_1).write(&mut chan_0_monitor_serialized).unwrap();
9713         get_monitor!(nodes[1], chan_id_2).write(&mut chan_1_monitor_serialized).unwrap();
9714
9715         persister = test_utils::TestPersister::new();
9716         let keys_manager = &chanmon_cfgs[1].keys_manager;
9717         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);
9718         nodes[1].chain_monitor = &new_chain_monitor;
9719
9720         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
9721         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9722                 &mut chan_0_monitor_read, keys_manager).unwrap();
9723         assert!(chan_0_monitor_read.is_empty());
9724         let mut chan_1_monitor_read = &chan_1_monitor_serialized.0[..];
9725         let (_, mut chan_1_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9726                 &mut chan_1_monitor_read, keys_manager).unwrap();
9727         assert!(chan_1_monitor_read.is_empty());
9728
9729         let mut nodes_1_read = &nodes_1_serialized[..];
9730         let (_, nodes_1_deserialized_tmp) = {
9731                 let mut channel_monitors = HashMap::new();
9732                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
9733                 channel_monitors.insert(chan_1_monitor.get_funding_txo().0, &mut chan_1_monitor);
9734                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_1_read, ChannelManagerReadArgs {
9735                         default_config: UserConfig::default(),
9736                         keys_manager,
9737                         fee_estimator: node_cfgs[1].fee_estimator,
9738                         chain_monitor: nodes[1].chain_monitor,
9739                         tx_broadcaster: nodes[1].tx_broadcaster.clone(),
9740                         logger: nodes[1].logger,
9741                         channel_monitors,
9742                 }).unwrap()
9743         };
9744         nodes_1_deserialized = nodes_1_deserialized_tmp;
9745         assert!(nodes_1_read.is_empty());
9746
9747         assert_eq!(nodes[1].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor),
9748                 ChannelMonitorUpdateStatus::Completed);
9749         assert_eq!(nodes[1].chain_monitor.watch_channel(chan_1_monitor.get_funding_txo().0, chan_1_monitor),
9750                 ChannelMonitorUpdateStatus::Completed);
9751         nodes[1].node = &nodes_1_deserialized;
9752         check_added_monitors!(nodes[1], 2);
9753
9754         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9755         // Note that nodes[1] and nodes[2] resend their channel_ready here since they haven't updated
9756         // the commitment state.
9757         reconnect_nodes(&nodes[1], &nodes[2], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9758
9759         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
9760
9761         expect_pending_htlcs_forwardable!(nodes[1]);
9762         expect_payment_received!(nodes[1], payment_hash, payment_secret, 100_000);
9763         check_added_monitors!(nodes[1], 1);
9764
9765         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9766         assert_eq!(events.len(), 1);
9767         let payment_event = SendEvent::from_event(events.pop().unwrap());
9768         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9769         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false);
9770         expect_pending_htlcs_forwardable!(nodes[2]);
9771         expect_payment_received!(nodes[2], payment_hash_2, payment_secret_2, 200_000);
9772
9773         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
9774         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage_2);
9775 }
9776
9777 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
9778         let chanmon_cfgs = create_chanmon_cfgs(2);
9779         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9780         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9781         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9782
9783         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9784
9785         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
9786                 .with_features(channelmanager::provided_invoice_features());
9787         let route = get_route!(nodes[0], payment_params, 10_000, TEST_FINAL_CLTV).unwrap();
9788
9789         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9790
9791         {
9792                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
9793                 check_added_monitors!(nodes[0], 1);
9794                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9795                 assert_eq!(events.len(), 1);
9796                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9797                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9798                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9799         }
9800         expect_pending_htlcs_forwardable!(nodes[1]);
9801         expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9802
9803         {
9804                 // Note that we use a different PaymentId here to allow us to duplicativly pay
9805                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_secret.0)).unwrap();
9806                 check_added_monitors!(nodes[0], 1);
9807                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9808                 assert_eq!(events.len(), 1);
9809                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9810                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9811                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9812                 // At this point, nodes[1] would notice it has too much value for the payment. It will
9813                 // assume the second is a privacy attack (no longer particularly relevant
9814                 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9815                 // the first HTLC delivered above.
9816         }
9817
9818         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9819         nodes[1].node.process_pending_htlc_forwards();
9820
9821         if test_for_second_fail_panic {
9822                 // Now we go fail back the first HTLC from the user end.
9823                 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9824
9825                 let expected_destinations = vec![
9826                         HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9827                         HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9828                 ];
9829                 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1],  expected_destinations);
9830                 nodes[1].node.process_pending_htlc_forwards();
9831
9832                 check_added_monitors!(nodes[1], 1);
9833                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9834                 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9835
9836                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9837                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9838                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9839
9840                 let failure_events = nodes[0].node.get_and_clear_pending_events();
9841                 assert_eq!(failure_events.len(), 2);
9842                 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9843                 if let Event::PaymentPathFailed { .. } = failure_events[1] {} else { panic!(); }
9844         } else {
9845                 // Let the second HTLC fail and claim the first
9846                 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9847                 nodes[1].node.process_pending_htlc_forwards();
9848
9849                 check_added_monitors!(nodes[1], 1);
9850                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9851                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9852                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9853
9854                 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9855
9856                 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9857         }
9858 }
9859
9860 #[test]
9861 fn test_dup_htlc_second_fail_panic() {
9862         // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9863         // value for the payment, we'd fail back both HTLCs after generating a `PaymentReceived` event.
9864         // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9865         // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9866         do_test_dup_htlc_second_rejected(true);
9867 }
9868
9869 #[test]
9870 fn test_dup_htlc_second_rejected() {
9871         // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9872         // simply reject the second HTLC but are still able to claim the first HTLC.
9873         do_test_dup_htlc_second_rejected(false);
9874 }
9875
9876 #[test]
9877 fn test_inconsistent_mpp_params() {
9878         // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9879         // such HTLC and allow the second to stay.
9880         let chanmon_cfgs = create_chanmon_cfgs(4);
9881         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9882         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9883         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9884
9885         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9886         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9887         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9888         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());
9889
9890         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id())
9891                 .with_features(channelmanager::provided_invoice_features());
9892         let mut route = get_route!(nodes[0], payment_params, 15_000_000, TEST_FINAL_CLTV).unwrap();
9893         assert_eq!(route.paths.len(), 2);
9894         route.paths.sort_by(|path_a, _| {
9895                 // Sort the path so that the path through nodes[1] comes first
9896                 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
9897                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9898         });
9899         let payment_params_opt = Some(payment_params);
9900
9901         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9902
9903         let cur_height = nodes[0].best_block_info().1;
9904         let payment_id = PaymentId([42; 32]);
9905
9906         let session_privs = {
9907                 // We create a fake route here so that we start with three pending HTLCs, which we'll
9908                 // ultimately have, just not right away.
9909                 let mut dup_route = route.clone();
9910                 dup_route.paths.push(route.paths[1].clone());
9911                 nodes[0].node.test_add_new_pending_payment(our_payment_hash, Some(our_payment_secret), payment_id, &dup_route).unwrap()
9912         };
9913         {
9914                 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();
9915                 check_added_monitors!(nodes[0], 1);
9916
9917                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9918                 assert_eq!(events.len(), 1);
9919                 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9920         }
9921         assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9922
9923         {
9924                 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();
9925                 check_added_monitors!(nodes[0], 1);
9926
9927                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9928                 assert_eq!(events.len(), 1);
9929                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9930
9931                 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9932                 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9933
9934                 expect_pending_htlcs_forwardable!(nodes[2]);
9935                 check_added_monitors!(nodes[2], 1);
9936
9937                 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9938                 assert_eq!(events.len(), 1);
9939                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9940
9941                 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9942                 check_added_monitors!(nodes[3], 0);
9943                 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9944
9945                 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9946                 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9947                 // post-payment_secrets) and fail back the new HTLC.
9948         }
9949         expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9950         nodes[3].node.process_pending_htlc_forwards();
9951         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9952         nodes[3].node.process_pending_htlc_forwards();
9953
9954         check_added_monitors!(nodes[3], 1);
9955
9956         let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9957         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9958         commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9959
9960         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 }]);
9961         check_added_monitors!(nodes[2], 1);
9962
9963         let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9964         nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9965         commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9966
9967         expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9968
9969         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();
9970         check_added_monitors!(nodes[0], 1);
9971
9972         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9973         assert_eq!(events.len(), 1);
9974         pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9975
9976         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9977 }
9978
9979 #[test]
9980 fn test_keysend_payments_to_public_node() {
9981         let chanmon_cfgs = create_chanmon_cfgs(2);
9982         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9983         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9984         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9985
9986         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9987         let network_graph = nodes[0].network_graph;
9988         let payer_pubkey = nodes[0].node.get_our_node_id();
9989         let payee_pubkey = nodes[1].node.get_our_node_id();
9990         let route_params = RouteParameters {
9991                 payment_params: PaymentParameters::for_keysend(payee_pubkey),
9992                 final_value_msat: 10000,
9993                 final_cltv_expiry_delta: 40,
9994         };
9995         let scorer = test_utils::TestScorer::with_penalty(0);
9996         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9997         let route = find_route(&payer_pubkey, &route_params, &network_graph, None, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
9998
9999         let test_preimage = PaymentPreimage([42; 32]);
10000         let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage), PaymentId(test_preimage.0)).unwrap();
10001         check_added_monitors!(nodes[0], 1);
10002         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
10003         assert_eq!(events.len(), 1);
10004         let event = events.pop().unwrap();
10005         let path = vec![&nodes[1]];
10006         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
10007         claim_payment(&nodes[0], &path, test_preimage);
10008 }
10009
10010 #[test]
10011 fn test_keysend_payments_to_private_node() {
10012         let chanmon_cfgs = create_chanmon_cfgs(2);
10013         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10014         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10015         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10016
10017         let payer_pubkey = nodes[0].node.get_our_node_id();
10018         let payee_pubkey = nodes[1].node.get_our_node_id();
10019         nodes[0].node.peer_connected(&payee_pubkey, &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
10020         nodes[1].node.peer_connected(&payer_pubkey, &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
10021
10022         let _chan = create_chan_between_nodes(&nodes[0], &nodes[1], channelmanager::provided_init_features(), channelmanager::provided_init_features());
10023         let route_params = RouteParameters {
10024                 payment_params: PaymentParameters::for_keysend(payee_pubkey),
10025                 final_value_msat: 10000,
10026                 final_cltv_expiry_delta: 40,
10027         };
10028         let network_graph = nodes[0].network_graph;
10029         let first_hops = nodes[0].node.list_usable_channels();
10030         let scorer = test_utils::TestScorer::with_penalty(0);
10031         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
10032         let route = find_route(
10033                 &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
10034                 nodes[0].logger, &scorer, &random_seed_bytes
10035         ).unwrap();
10036
10037         let test_preimage = PaymentPreimage([42; 32]);
10038         let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage), PaymentId(test_preimage.0)).unwrap();
10039         check_added_monitors!(nodes[0], 1);
10040         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
10041         assert_eq!(events.len(), 1);
10042         let event = events.pop().unwrap();
10043         let path = vec![&nodes[1]];
10044         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
10045         claim_payment(&nodes[0], &path, test_preimage);
10046 }
10047
10048 #[test]
10049 fn test_double_partial_claim() {
10050         // Test what happens if a node receives a payment, generates a PaymentReceived event, the HTLCs
10051         // time out, the sender resends only some of the MPP parts, then the user processes the
10052         // PaymentReceived event, ensuring they don't inadvertently claim only part of the full payment
10053         // amount.
10054         let chanmon_cfgs = create_chanmon_cfgs(4);
10055         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
10056         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
10057         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
10058
10059         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
10060         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
10061         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
10062         create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
10063
10064         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
10065         assert_eq!(route.paths.len(), 2);
10066         route.paths.sort_by(|path_a, _| {
10067                 // Sort the path so that the path through nodes[1] comes first
10068                 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
10069                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
10070         });
10071
10072         send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 15_000_000, payment_hash, payment_secret);
10073         // nodes[3] has now received a PaymentReceived event...which it will take some (exorbitant)
10074         // amount of time to respond to.
10075
10076         // Connect some blocks to time out the payment
10077         connect_blocks(&nodes[3], TEST_FINAL_CLTV);
10078         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // To get the same height for sending later
10079
10080         let failed_destinations = vec![
10081                 HTLCDestination::FailedPayment { payment_hash },
10082                 HTLCDestination::FailedPayment { payment_hash },
10083         ];
10084         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations);
10085
10086         pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash);
10087
10088         // nodes[1] now retries one of the two paths...
10089         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
10090         check_added_monitors!(nodes[0], 2);
10091
10092         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
10093         assert_eq!(events.len(), 2);
10094         pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
10095
10096         // At this point nodes[3] has received one half of the payment, and the user goes to handle
10097         // that PaymentReceived event they got hours ago and never handled...we should refuse to claim.
10098         nodes[3].node.claim_funds(payment_preimage);
10099         check_added_monitors!(nodes[3], 0);
10100         assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
10101 }
10102
10103 fn do_test_partial_claim_before_restart(persist_both_monitors: bool) {
10104         // Test what happens if a node receives an MPP payment, claims it, but crashes before
10105         // persisting the ChannelManager. If `persist_both_monitors` is false, also crash after only
10106         // updating one of the two channels' ChannelMonitors. As a result, on startup, we'll (a) still
10107         // have the PaymentReceived event, (b) have one (or two) channel(s) that goes on chain with the
10108         // HTLC preimage in them, and (c) optionally have one channel that is live off-chain but does
10109         // not have the preimage tied to the still-pending HTLC.
10110         //
10111         // To get to the correct state, on startup we should propagate the preimage to the
10112         // still-off-chain channel, claiming the HTLC as soon as the peer connects, with the monitor
10113         // receiving the preimage without a state update.
10114         //
10115         // Further, we should generate a `PaymentClaimed` event to inform the user that the payment was
10116         // definitely claimed.
10117         let chanmon_cfgs = create_chanmon_cfgs(4);
10118         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
10119         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
10120
10121         let persister: test_utils::TestPersister;
10122         let new_chain_monitor: test_utils::TestChainMonitor;
10123         let nodes_3_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
10124
10125         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
10126
10127         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
10128         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
10129         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;
10130         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;
10131
10132         // Create an MPP route for 15k sats, more than the default htlc-max of 10%
10133         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
10134         assert_eq!(route.paths.len(), 2);
10135         route.paths.sort_by(|path_a, _| {
10136                 // Sort the path so that the path through nodes[1] comes first
10137                 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
10138                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
10139         });
10140
10141         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
10142         check_added_monitors!(nodes[0], 2);
10143
10144         // Send the payment through to nodes[3] *without* clearing the PaymentReceived event
10145         let mut send_events = nodes[0].node.get_and_clear_pending_msg_events();
10146         assert_eq!(send_events.len(), 2);
10147         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);
10148         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);
10149
10150         // Now that we have an MPP payment pending, get the latest encoded copies of nodes[3]'s
10151         // monitors and ChannelManager, for use later, if we don't want to persist both monitors.
10152         let mut original_monitor = test_utils::TestVecWriter(Vec::new());
10153         if !persist_both_monitors {
10154                 for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
10155                         if outpoint.to_channel_id() == chan_id_not_persisted {
10156                                 assert!(original_monitor.0.is_empty());
10157                                 nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut original_monitor).unwrap();
10158                         }
10159                 }
10160         }
10161
10162         let mut original_manager = test_utils::TestVecWriter(Vec::new());
10163         nodes[3].node.write(&mut original_manager).unwrap();
10164
10165         expect_payment_received!(nodes[3], payment_hash, payment_secret, 15_000_000);
10166
10167         nodes[3].node.claim_funds(payment_preimage);
10168         check_added_monitors!(nodes[3], 2);
10169         expect_payment_claimed!(nodes[3], payment_hash, 15_000_000);
10170
10171         // Now fetch one of the two updated ChannelMonitors from nodes[3], and restart pretending we
10172         // crashed in between the two persistence calls - using one old ChannelMonitor and one new one,
10173         // with the old ChannelManager.
10174         let mut updated_monitor = test_utils::TestVecWriter(Vec::new());
10175         for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
10176                 if outpoint.to_channel_id() == chan_id_persisted {
10177                         assert!(updated_monitor.0.is_empty());
10178                         nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut updated_monitor).unwrap();
10179                 }
10180         }
10181         // If `persist_both_monitors` is set, get the second monitor here as well
10182         if persist_both_monitors {
10183                 for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
10184                         if outpoint.to_channel_id() == chan_id_not_persisted {
10185                                 assert!(original_monitor.0.is_empty());
10186                                 nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut original_monitor).unwrap();
10187                         }
10188                 }
10189         }
10190
10191         // Now restart nodes[3].
10192         persister = test_utils::TestPersister::new();
10193         let keys_manager = &chanmon_cfgs[3].keys_manager;
10194         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);
10195         nodes[3].chain_monitor = &new_chain_monitor;
10196         let mut monitors = Vec::new();
10197         for mut monitor_data in [original_monitor, updated_monitor].iter() {
10198                 let (_, mut deserialized_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut &monitor_data.0[..], keys_manager).unwrap();
10199                 monitors.push(deserialized_monitor);
10200         }
10201
10202         let config = UserConfig::default();
10203         nodes_3_deserialized = {
10204                 let mut channel_monitors = HashMap::new();
10205                 for monitor in monitors.iter_mut() {
10206                         channel_monitors.insert(monitor.get_funding_txo().0, monitor);
10207                 }
10208                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut &original_manager.0[..], ChannelManagerReadArgs {
10209                         default_config: config,
10210                         keys_manager,
10211                         fee_estimator: node_cfgs[3].fee_estimator,
10212                         chain_monitor: nodes[3].chain_monitor,
10213                         tx_broadcaster: nodes[3].tx_broadcaster.clone(),
10214                         logger: nodes[3].logger,
10215                         channel_monitors,
10216                 }).unwrap().1
10217         };
10218         nodes[3].node = &nodes_3_deserialized;
10219
10220         for monitor in monitors {
10221                 // On startup the preimage should have been copied into the non-persisted monitor:
10222                 assert!(monitor.get_stored_preimages().contains_key(&payment_hash));
10223                 assert_eq!(nodes[3].chain_monitor.watch_channel(monitor.get_funding_txo().0.clone(), monitor),
10224                         ChannelMonitorUpdateStatus::Completed);
10225         }
10226         check_added_monitors!(nodes[3], 2);
10227
10228         nodes[1].node.peer_disconnected(&nodes[3].node.get_our_node_id(), false);
10229         nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), false);
10230
10231         // During deserialization, we should have closed one channel and broadcast its latest
10232         // commitment transaction. We should also still have the original PaymentReceived event we
10233         // never finished processing.
10234         let events = nodes[3].node.get_and_clear_pending_events();
10235         assert_eq!(events.len(), if persist_both_monitors { 4 } else { 3 });
10236         if let Event::PaymentReceived { amount_msat: 15_000_000, .. } = events[0] { } else { panic!(); }
10237         if let Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } = events[1] { } else { panic!(); }
10238         if persist_both_monitors {
10239                 if let Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } = events[2] { } else { panic!(); }
10240         }
10241
10242         // On restart, we should also get a duplicate PaymentClaimed event as we persisted the
10243         // ChannelManager prior to handling the original one.
10244         if let Event::PaymentClaimed { payment_hash: our_payment_hash, amount_msat: 15_000_000, .. } =
10245                 events[if persist_both_monitors { 3 } else { 2 }]
10246         {
10247                 assert_eq!(payment_hash, our_payment_hash);
10248         } else { panic!(); }
10249
10250         assert_eq!(nodes[3].node.list_channels().len(), if persist_both_monitors { 0 } else { 1 });
10251         if !persist_both_monitors {
10252                 // If one of the two channels is still live, reveal the payment preimage over it.
10253
10254                 nodes[3].node.peer_connected(&nodes[2].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
10255                 let reestablish_1 = get_chan_reestablish_msgs!(nodes[3], nodes[2]);
10256                 nodes[2].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
10257                 let reestablish_2 = get_chan_reestablish_msgs!(nodes[2], nodes[3]);
10258
10259                 nodes[2].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish_1[0]);
10260                 get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, nodes[3].node.get_our_node_id());
10261                 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
10262
10263                 nodes[3].node.handle_channel_reestablish(&nodes[2].node.get_our_node_id(), &reestablish_2[0]);
10264
10265                 // Once we call `get_and_clear_pending_msg_events` the holding cell is cleared and the HTLC
10266                 // claim should fly.
10267                 let ds_msgs = nodes[3].node.get_and_clear_pending_msg_events();
10268                 check_added_monitors!(nodes[3], 1);
10269                 assert_eq!(ds_msgs.len(), 2);
10270                 if let MessageSendEvent::SendChannelUpdate { .. } = ds_msgs[1] {} else { panic!(); }
10271
10272                 let cs_updates = match ds_msgs[0] {
10273                         MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
10274                                 nodes[2].node.handle_update_fulfill_htlc(&nodes[3].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
10275                                 check_added_monitors!(nodes[2], 1);
10276                                 let cs_updates = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
10277                                 expect_payment_forwarded!(nodes[2], nodes[0], nodes[3], Some(1000), false, false);
10278                                 commitment_signed_dance!(nodes[2], nodes[3], updates.commitment_signed, false, true);
10279                                 cs_updates
10280                         }
10281                         _ => panic!(),
10282                 };
10283
10284                 nodes[0].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &cs_updates.update_fulfill_htlcs[0]);
10285                 commitment_signed_dance!(nodes[0], nodes[2], cs_updates.commitment_signed, false, true);
10286                 expect_payment_sent!(nodes[0], payment_preimage);
10287         }
10288 }
10289
10290 #[test]
10291 fn test_partial_claim_before_restart() {
10292         do_test_partial_claim_before_restart(false);
10293         do_test_partial_claim_before_restart(true);
10294 }
10295
10296 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
10297 #[derive(Clone, Copy, PartialEq)]
10298 enum ExposureEvent {
10299         /// Breach occurs at HTLC forwarding (see `send_htlc`)
10300         AtHTLCForward,
10301         /// Breach occurs at HTLC reception (see `update_add_htlc`)
10302         AtHTLCReception,
10303         /// Breach occurs at outbound update_fee (see `send_update_fee`)
10304         AtUpdateFeeOutbound,
10305 }
10306
10307 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool) {
10308         // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
10309         // policy.
10310         //
10311         // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
10312         // trimmed-to-dust HTLC outbound balance and this new payment as included on next
10313         // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
10314         // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
10315         // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
10316         // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
10317         // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
10318         // might be available again for HTLC processing once the dust bandwidth has cleared up.
10319
10320         let chanmon_cfgs = create_chanmon_cfgs(2);
10321         let mut config = test_default_channel_config();
10322         config.channel_config.max_dust_htlc_exposure_msat = 5_000_000; // default setting value
10323         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10324         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
10325         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10326
10327         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
10328         let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10329         open_channel.max_htlc_value_in_flight_msat = 50_000_000;
10330         open_channel.max_accepted_htlcs = 60;
10331         if on_holder_tx {
10332                 open_channel.dust_limit_satoshis = 546;
10333         }
10334         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_channel);
10335         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10336         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_channel);
10337
10338         let opt_anchors = false;
10339
10340         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
10341
10342         if on_holder_tx {
10343                 if let Some(mut chan) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&temporary_channel_id) {
10344                         chan.holder_dust_limit_satoshis = 546;
10345                 }
10346         }
10347
10348         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
10349         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()));
10350         check_added_monitors!(nodes[1], 1);
10351
10352         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()));
10353         check_added_monitors!(nodes[0], 1);
10354
10355         let (channel_ready, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
10356         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
10357         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
10358
10359         let dust_buffer_feerate = {
10360                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
10361                 let chan = chan_lock.by_id.get(&channel_id).unwrap();
10362                 chan.get_dust_buffer_feerate(None) as u64
10363         };
10364         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;
10365         let dust_outbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
10366
10367         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;
10368         let dust_inbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
10369
10370         let dust_htlc_on_counterparty_tx: u64 = 25;
10371         let dust_htlc_on_counterparty_tx_msat: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
10372
10373         if on_holder_tx {
10374                 if dust_outbound_balance {
10375                         // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
10376                         // Outbound dust balance: 4372 sats
10377                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
10378                         for i in 0..dust_outbound_htlc_on_holder_tx {
10379                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
10380                                 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); }
10381                         }
10382                 } else {
10383                         // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
10384                         // Inbound dust balance: 4372 sats
10385                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
10386                         for _ in 0..dust_inbound_htlc_on_holder_tx {
10387                                 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
10388                         }
10389                 }
10390         } else {
10391                 if dust_outbound_balance {
10392                         // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
10393                         // Outbound dust balance: 5000 sats
10394                         for i in 0..dust_htlc_on_counterparty_tx {
10395                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
10396                                 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); }
10397                         }
10398                 } else {
10399                         // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
10400                         // Inbound dust balance: 5000 sats
10401                         for _ in 0..dust_htlc_on_counterparty_tx {
10402                                 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
10403                         }
10404                 }
10405         }
10406
10407         let dust_overflow = dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx + 1);
10408         if exposure_breach_event == ExposureEvent::AtHTLCForward {
10409                 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 });
10410                 let mut config = UserConfig::default();
10411                 // With default dust exposure: 5000 sats
10412                 if on_holder_tx {
10413                         let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * (dust_outbound_htlc_on_holder_tx + 1);
10414                         let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * dust_inbound_htlc_on_holder_tx + dust_outbound_htlc_on_holder_tx_msat;
10415                         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)));
10416                 } else {
10417                         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)));
10418                 }
10419         } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
10420                 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 });
10421                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
10422                 check_added_monitors!(nodes[1], 1);
10423                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
10424                 assert_eq!(events.len(), 1);
10425                 let payment_event = SendEvent::from_event(events.remove(0));
10426                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
10427                 // With default dust exposure: 5000 sats
10428                 if on_holder_tx {
10429                         // Outbound dust balance: 6399 sats
10430                         let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
10431                         let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
10432                         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);
10433                 } else {
10434                         // Outbound dust balance: 5200 sats
10435                         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);
10436                 }
10437         } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
10438                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 2_500_000);
10439                 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", ); }
10440                 {
10441                         let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
10442                         *feerate_lock = *feerate_lock * 10;
10443                 }
10444                 nodes[0].node.timer_tick_occurred();
10445                 check_added_monitors!(nodes[0], 1);
10446                 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);
10447         }
10448
10449         let _ = nodes[0].node.get_and_clear_pending_msg_events();
10450         let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
10451         added_monitors.clear();
10452 }
10453
10454 #[test]
10455 fn test_max_dust_htlc_exposure() {
10456         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true);
10457         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true);
10458         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true);
10459         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false);
10460         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false);
10461         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false);
10462         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true);
10463         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false);
10464         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true);
10465         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false);
10466         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false);
10467         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true);
10468 }
10469
10470 #[test]
10471 fn test_non_final_funding_tx() {
10472         let chanmon_cfgs = create_chanmon_cfgs(2);
10473         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10474         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10475         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10476
10477         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
10478         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10479         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_channel_message);
10480         let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10481         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_channel_message);
10482
10483         let best_height = nodes[0].node.best_block.read().unwrap().height();
10484
10485         let chan_id = *nodes[0].network_chan_count.borrow();
10486         let events = nodes[0].node.get_and_clear_pending_events();
10487         let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::Script::new(), sequence: Sequence(1), witness: Witness::from_vec(vec!(vec!(1))) };
10488         assert_eq!(events.len(), 1);
10489         let mut tx = match events[0] {
10490                 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
10491                         // Timelock the transaction _beyond_ the best client height + 2.
10492                         Transaction { version: chan_id as i32, lock_time: PackedLockTime(best_height + 3), input: vec![input], output: vec![TxOut {
10493                                 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
10494                         }]}
10495                 },
10496                 _ => panic!("Unexpected event"),
10497         };
10498         // Transaction should fail as it's evaluated as non-final for propagation.
10499         match nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()) {
10500                 Err(APIError::APIMisuseError { err }) => {
10501                         assert_eq!(format!("Funding transaction absolute timelock is non-final"), err);
10502                 },
10503                 _ => panic!()
10504         }
10505
10506         // However, transaction should be accepted if it's in a +2 headroom from best block.
10507         tx.lock_time = PackedLockTime(tx.lock_time.0 - 1);
10508         assert!(nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
10509         get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
10510 }