30120225bd25a78de6e00f1f4783d75d0ee05d97
[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, PAYMENT_EXPIRY_BLOCKS};
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         assert!(ANTI_REORG_DELAY > PAYMENT_EXPIRY_BLOCKS); // We assume payments will also expire
3188
3189         let events = nodes[1].node.get_and_clear_pending_events();
3190         assert_eq!(events.len(), if deliver_bs_raa { 2 + (nodes.len() - 1) } else { 4 + nodes.len() });
3191         match events[0] {
3192                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3193                 _ => panic!("Unexepected event"),
3194         }
3195         match events[1] {
3196                 Event::PaymentPathFailed { ref payment_hash, .. } => {
3197                         assert_eq!(*payment_hash, fourth_payment_hash);
3198                 },
3199                 _ => panic!("Unexpected event"),
3200         }
3201         if !deliver_bs_raa {
3202                 match events[2] {
3203                         Event::PaymentFailed { ref payment_hash, .. } => {
3204                                 assert_eq!(*payment_hash, fourth_payment_hash);
3205                         },
3206                         _ => panic!("Unexpected event"),
3207                 }
3208                 match events[3] {
3209                         Event::PendingHTLCsForwardable { .. } => { },
3210                         _ => panic!("Unexpected event"),
3211                 };
3212         }
3213         nodes[1].node.process_pending_htlc_forwards();
3214         check_added_monitors!(nodes[1], 1);
3215
3216         let events = nodes[1].node.get_and_clear_pending_msg_events();
3217         assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3218         match events[if deliver_bs_raa { 1 } else { 0 }] {
3219                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3220                 _ => panic!("Unexpected event"),
3221         }
3222         match events[if deliver_bs_raa { 2 } else { 1 }] {
3223                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3224                         assert_eq!(channel_id, chan_2.2);
3225                         assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3226                 },
3227                 _ => panic!("Unexpected event"),
3228         }
3229         if deliver_bs_raa {
3230                 match events[0] {
3231                         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, .. } } => {
3232                                 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3233                                 assert_eq!(update_add_htlcs.len(), 1);
3234                                 assert!(update_fulfill_htlcs.is_empty());
3235                                 assert!(update_fail_htlcs.is_empty());
3236                                 assert!(update_fail_malformed_htlcs.is_empty());
3237                         },
3238                         _ => panic!("Unexpected event"),
3239                 }
3240         }
3241         match events[if deliver_bs_raa { 3 } else { 2 }] {
3242                 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, .. } } => {
3243                         assert!(update_add_htlcs.is_empty());
3244                         assert_eq!(update_fail_htlcs.len(), 3);
3245                         assert!(update_fulfill_htlcs.is_empty());
3246                         assert!(update_fail_malformed_htlcs.is_empty());
3247                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3248
3249                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3250                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3251                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3252
3253                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3254
3255                         let events = nodes[0].node.get_and_clear_pending_events();
3256                         assert_eq!(events.len(), 3);
3257                         match events[0] {
3258                                 Event::PaymentPathFailed { ref payment_hash, ref network_update, .. } => {
3259                                         assert!(failed_htlcs.insert(payment_hash.0));
3260                                         // If we delivered B's RAA we got an unknown preimage error, not something
3261                                         // that we should update our routing table for.
3262                                         if !deliver_bs_raa {
3263                                                 assert!(network_update.is_some());
3264                                         }
3265                                 },
3266                                 _ => panic!("Unexpected event"),
3267                         }
3268                         match events[1] {
3269                                 Event::PaymentPathFailed { ref payment_hash, ref network_update, .. } => {
3270                                         assert!(failed_htlcs.insert(payment_hash.0));
3271                                         assert!(network_update.is_some());
3272                                 },
3273                                 _ => panic!("Unexpected event"),
3274                         }
3275                         match events[2] {
3276                                 Event::PaymentPathFailed { ref payment_hash, ref network_update, .. } => {
3277                                         assert!(failed_htlcs.insert(payment_hash.0));
3278                                         assert!(network_update.is_some());
3279                                 },
3280                                 _ => panic!("Unexpected event"),
3281                         }
3282                 },
3283                 _ => panic!("Unexpected event"),
3284         }
3285
3286         assert!(failed_htlcs.contains(&first_payment_hash.0));
3287         assert!(failed_htlcs.contains(&second_payment_hash.0));
3288         assert!(failed_htlcs.contains(&third_payment_hash.0));
3289 }
3290
3291 #[test]
3292 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3293         do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3294         do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3295         do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3296         do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3297 }
3298
3299 #[test]
3300 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3301         do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3302         do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3303         do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3304         do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3305 }
3306
3307 #[test]
3308 fn fail_backward_pending_htlc_upon_channel_failure() {
3309         let chanmon_cfgs = create_chanmon_cfgs(2);
3310         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3311         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3312         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3313         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());
3314
3315         // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3316         {
3317                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3318                 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
3319                 check_added_monitors!(nodes[0], 1);
3320
3321                 let payment_event = {
3322                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3323                         assert_eq!(events.len(), 1);
3324                         SendEvent::from_event(events.remove(0))
3325                 };
3326                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3327                 assert_eq!(payment_event.msgs.len(), 1);
3328         }
3329
3330         // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3331         let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3332         {
3333                 nodes[0].node.send_payment(&route, failed_payment_hash, &Some(failed_payment_secret), PaymentId(failed_payment_hash.0)).unwrap();
3334                 check_added_monitors!(nodes[0], 0);
3335
3336                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3337         }
3338
3339         // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3340         {
3341                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3342
3343                 let secp_ctx = Secp256k1::new();
3344                 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3345                 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3346                 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &Some(payment_secret), current_height, &None).unwrap();
3347                 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3348                 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3349
3350                 // Send a 0-msat update_add_htlc to fail the channel.
3351                 let update_add_htlc = msgs::UpdateAddHTLC {
3352                         channel_id: chan.2,
3353                         htlc_id: 0,
3354                         amount_msat: 0,
3355                         payment_hash,
3356                         cltv_expiry,
3357                         onion_routing_packet,
3358                 };
3359                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3360         }
3361         let events = nodes[0].node.get_and_clear_pending_events();
3362         assert_eq!(events.len(), 2);
3363         // Check that Alice fails backward the pending HTLC from the second payment.
3364         match events[0] {
3365                 Event::PaymentPathFailed { payment_hash, .. } => {
3366                         assert_eq!(payment_hash, failed_payment_hash);
3367                 },
3368                 _ => panic!("Unexpected event"),
3369         }
3370         match events[1] {
3371                 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3372                         assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3373                 },
3374                 _ => panic!("Unexpected event {:?}", events[1]),
3375         }
3376         check_closed_broadcast!(nodes[0], true);
3377         check_added_monitors!(nodes[0], 1);
3378 }
3379
3380 #[test]
3381 fn test_htlc_ignore_latest_remote_commitment() {
3382         // Test that HTLC transactions spending the latest remote commitment transaction are simply
3383         // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3384         let chanmon_cfgs = create_chanmon_cfgs(2);
3385         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3386         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3387         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3388         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3389
3390         route_payment(&nodes[0], &[&nodes[1]], 10000000);
3391         nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3392         connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3393         check_closed_broadcast!(nodes[0], true);
3394         check_added_monitors!(nodes[0], 1);
3395         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
3396
3397         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3398         assert_eq!(node_txn.len(), 3);
3399         assert_eq!(node_txn[0], node_txn[1]);
3400
3401         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
3402         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3403         check_closed_broadcast!(nodes[1], true);
3404         check_added_monitors!(nodes[1], 1);
3405         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3406
3407         // Duplicate the connect_block call since this may happen due to other listeners
3408         // registering new transactions
3409         header.prev_blockhash = header.block_hash();
3410         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[2].clone()]});
3411 }
3412
3413 #[test]
3414 fn test_force_close_fail_back() {
3415         // Check which HTLCs are failed-backwards on channel force-closure
3416         let chanmon_cfgs = create_chanmon_cfgs(3);
3417         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3418         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3419         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3420         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3421         create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3422
3423         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3424
3425         let mut payment_event = {
3426                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
3427                 check_added_monitors!(nodes[0], 1);
3428
3429                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3430                 assert_eq!(events.len(), 1);
3431                 SendEvent::from_event(events.remove(0))
3432         };
3433
3434         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3435         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3436
3437         expect_pending_htlcs_forwardable!(nodes[1]);
3438
3439         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3440         assert_eq!(events_2.len(), 1);
3441         payment_event = SendEvent::from_event(events_2.remove(0));
3442         assert_eq!(payment_event.msgs.len(), 1);
3443
3444         check_added_monitors!(nodes[1], 1);
3445         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3446         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3447         check_added_monitors!(nodes[2], 1);
3448         let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3449
3450         // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3451         // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3452         // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3453
3454         nodes[2].node.force_close_broadcasting_latest_txn(&payment_event.commitment_msg.channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3455         check_closed_broadcast!(nodes[2], true);
3456         check_added_monitors!(nodes[2], 1);
3457         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
3458         let tx = {
3459                 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3460                 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3461                 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3462                 // back to nodes[1] upon timeout otherwise.
3463                 assert_eq!(node_txn.len(), 1);
3464                 node_txn.remove(0)
3465         };
3466
3467         mine_transaction(&nodes[1], &tx);
3468
3469         // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3470         check_closed_broadcast!(nodes[1], true);
3471         check_added_monitors!(nodes[1], 1);
3472         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3473
3474         // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3475         {
3476                 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3477                         .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);
3478         }
3479         mine_transaction(&nodes[2], &tx);
3480         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3481         assert_eq!(node_txn.len(), 1);
3482         assert_eq!(node_txn[0].input.len(), 1);
3483         assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3484         assert_eq!(node_txn[0].lock_time.0, 0); // Must be an HTLC-Success
3485         assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3486
3487         check_spends!(node_txn[0], tx);
3488 }
3489
3490 #[test]
3491 fn test_dup_events_on_peer_disconnect() {
3492         // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3493         // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3494         // as we used to generate the event immediately upon receipt of the payment preimage in the
3495         // update_fulfill_htlc message.
3496
3497         let chanmon_cfgs = create_chanmon_cfgs(2);
3498         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3499         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3500         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3501         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3502
3503         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3504
3505         nodes[1].node.claim_funds(payment_preimage);
3506         expect_payment_claimed!(nodes[1], payment_hash, 1_000_000);
3507         check_added_monitors!(nodes[1], 1);
3508         let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3509         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3510         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
3511
3512         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3513         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3514
3515         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3516         expect_payment_path_successful!(nodes[0]);
3517 }
3518
3519 #[test]
3520 fn test_peer_disconnected_before_funding_broadcasted() {
3521         // Test that channels are closed with `ClosureReason::DisconnectedPeer` if the peer disconnects
3522         // before the funding transaction has been broadcasted.
3523         let chanmon_cfgs = create_chanmon_cfgs(2);
3524         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3525         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3526         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3527
3528         // Open a channel between `nodes[0]` and `nodes[1]`, for which the funding transaction is never
3529         // broadcasted, even though it's created by `nodes[0]`.
3530         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();
3531         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
3532         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_channel);
3533         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
3534         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_channel);
3535
3536         let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
3537         assert_eq!(temporary_channel_id, expected_temporary_channel_id);
3538
3539         assert!(nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
3540
3541         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
3542         assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
3543
3544         // Even though the funding transaction is created by `nodes[0]`, the `FundingCreated` msg is
3545         // never sent to `nodes[1]`, and therefore the tx is never signed by either party nor
3546         // broadcasted.
3547         {
3548                 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
3549         }
3550
3551         // Ensure that the channel is closed with `ClosureReason::DisconnectedPeer` when the peers are
3552         // disconnected before the funding transaction was broadcasted.
3553         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3554         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3555
3556         check_closed_event!(nodes[0], 1, ClosureReason::DisconnectedPeer);
3557         check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
3558 }
3559
3560 #[test]
3561 fn test_simple_peer_disconnect() {
3562         // Test that we can reconnect when there are no lost messages
3563         let chanmon_cfgs = create_chanmon_cfgs(3);
3564         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3565         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3566         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3567         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3568         create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3569
3570         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3571         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3572         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3573
3574         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3575         let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3576         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3577         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3578
3579         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3580         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3581         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3582
3583         let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3584         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3585         let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3586         let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3587
3588         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3589         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3590
3591         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3592         fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3593
3594         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3595         {
3596                 let events = nodes[0].node.get_and_clear_pending_events();
3597                 assert_eq!(events.len(), 3);
3598                 match events[0] {
3599                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3600                                 assert_eq!(payment_preimage, payment_preimage_3);
3601                                 assert_eq!(payment_hash, payment_hash_3);
3602                         },
3603                         _ => panic!("Unexpected event"),
3604                 }
3605                 match events[1] {
3606                         Event::PaymentPathFailed { payment_hash, payment_failed_permanently, .. } => {
3607                                 assert_eq!(payment_hash, payment_hash_5);
3608                                 assert!(payment_failed_permanently);
3609                         },
3610                         _ => panic!("Unexpected event"),
3611                 }
3612                 match events[2] {
3613                         Event::PaymentPathSuccessful { .. } => {},
3614                         _ => panic!("Unexpected event"),
3615                 }
3616         }
3617
3618         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3619         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3620 }
3621
3622 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3623         // Test that we can reconnect when in-flight HTLC updates get dropped
3624         let chanmon_cfgs = create_chanmon_cfgs(2);
3625         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3626         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3627         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3628
3629         let mut as_channel_ready = None;
3630         if messages_delivered == 0 {
3631                 let (channel_ready, _, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3632                 as_channel_ready = Some(channel_ready);
3633                 // nodes[1] doesn't receive the channel_ready message (it'll be re-sent on reconnect)
3634                 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3635                 // it before the channel_reestablish message.
3636         } else {
3637                 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3638         }
3639
3640         let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1_000_000);
3641
3642         let payment_event = {
3643                 nodes[0].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
3644                 check_added_monitors!(nodes[0], 1);
3645
3646                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3647                 assert_eq!(events.len(), 1);
3648                 SendEvent::from_event(events.remove(0))
3649         };
3650         assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3651
3652         if messages_delivered < 2 {
3653                 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3654         } else {
3655                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3656                 if messages_delivered >= 3 {
3657                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3658                         check_added_monitors!(nodes[1], 1);
3659                         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3660
3661                         if messages_delivered >= 4 {
3662                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3663                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3664                                 check_added_monitors!(nodes[0], 1);
3665
3666                                 if messages_delivered >= 5 {
3667                                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3668                                         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3669                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3670                                         check_added_monitors!(nodes[0], 1);
3671
3672                                         if messages_delivered >= 6 {
3673                                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3674                                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3675                                                 check_added_monitors!(nodes[1], 1);
3676                                         }
3677                                 }
3678                         }
3679                 }
3680         }
3681
3682         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3683         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3684         if messages_delivered < 3 {
3685                 if simulate_broken_lnd {
3686                         // lnd has a long-standing bug where they send a channel_ready prior to a
3687                         // channel_reestablish if you reconnect prior to channel_ready time.
3688                         //
3689                         // Here we simulate that behavior, delivering a channel_ready immediately on
3690                         // reconnect. Note that we don't bother skipping the now-duplicate channel_ready sent
3691                         // in `reconnect_nodes` but we currently don't fail based on that.
3692                         //
3693                         // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3694                         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready.as_ref().unwrap().0);
3695                 }
3696                 // Even if the channel_ready messages get exchanged, as long as nothing further was
3697                 // received on either side, both sides will need to resend them.
3698                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3699         } else if messages_delivered == 3 {
3700                 // nodes[0] still wants its RAA + commitment_signed
3701                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3702         } else if messages_delivered == 4 {
3703                 // nodes[0] still wants its commitment_signed
3704                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3705         } else if messages_delivered == 5 {
3706                 // nodes[1] still wants its final RAA
3707                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3708         } else if messages_delivered == 6 {
3709                 // Everything was delivered...
3710                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3711         }
3712
3713         let events_1 = nodes[1].node.get_and_clear_pending_events();
3714         assert_eq!(events_1.len(), 1);
3715         match events_1[0] {
3716                 Event::PendingHTLCsForwardable { .. } => { },
3717                 _ => panic!("Unexpected event"),
3718         };
3719
3720         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3721         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3722         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3723
3724         nodes[1].node.process_pending_htlc_forwards();
3725
3726         let events_2 = nodes[1].node.get_and_clear_pending_events();
3727         assert_eq!(events_2.len(), 1);
3728         match events_2[0] {
3729                 Event::PaymentReceived { ref payment_hash, ref purpose, amount_msat } => {
3730                         assert_eq!(payment_hash_1, *payment_hash);
3731                         assert_eq!(amount_msat, 1_000_000);
3732                         match &purpose {
3733                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3734                                         assert!(payment_preimage.is_none());
3735                                         assert_eq!(payment_secret_1, *payment_secret);
3736                                 },
3737                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
3738                         }
3739                 },
3740                 _ => panic!("Unexpected event"),
3741         }
3742
3743         nodes[1].node.claim_funds(payment_preimage_1);
3744         check_added_monitors!(nodes[1], 1);
3745         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3746
3747         let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3748         assert_eq!(events_3.len(), 1);
3749         let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3750                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3751                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3752                         assert!(updates.update_add_htlcs.is_empty());
3753                         assert!(updates.update_fail_htlcs.is_empty());
3754                         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3755                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3756                         assert!(updates.update_fee.is_none());
3757                         (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3758                 },
3759                 _ => panic!("Unexpected event"),
3760         };
3761
3762         if messages_delivered >= 1 {
3763                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3764
3765                 let events_4 = nodes[0].node.get_and_clear_pending_events();
3766                 assert_eq!(events_4.len(), 1);
3767                 match events_4[0] {
3768                         Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3769                                 assert_eq!(payment_preimage_1, *payment_preimage);
3770                                 assert_eq!(payment_hash_1, *payment_hash);
3771                         },
3772                         _ => panic!("Unexpected event"),
3773                 }
3774
3775                 if messages_delivered >= 2 {
3776                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3777                         check_added_monitors!(nodes[0], 1);
3778                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3779
3780                         if messages_delivered >= 3 {
3781                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3782                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3783                                 check_added_monitors!(nodes[1], 1);
3784
3785                                 if messages_delivered >= 4 {
3786                                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3787                                         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3788                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3789                                         check_added_monitors!(nodes[1], 1);
3790
3791                                         if messages_delivered >= 5 {
3792                                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3793                                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3794                                                 check_added_monitors!(nodes[0], 1);
3795                                         }
3796                                 }
3797                         }
3798                 }
3799         }
3800
3801         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3802         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3803         if messages_delivered < 2 {
3804                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3805                 if messages_delivered < 1 {
3806                         expect_payment_sent!(nodes[0], payment_preimage_1);
3807                 } else {
3808                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3809                 }
3810         } else if messages_delivered == 2 {
3811                 // nodes[0] still wants its RAA + commitment_signed
3812                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3813         } else if messages_delivered == 3 {
3814                 // nodes[0] still wants its commitment_signed
3815                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3816         } else if messages_delivered == 4 {
3817                 // nodes[1] still wants its final RAA
3818                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3819         } else if messages_delivered == 5 {
3820                 // Everything was delivered...
3821                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3822         }
3823
3824         if messages_delivered == 1 || messages_delivered == 2 {
3825                 expect_payment_path_successful!(nodes[0]);
3826         }
3827
3828         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3829         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3830         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3831
3832         if messages_delivered > 2 {
3833                 expect_payment_path_successful!(nodes[0]);
3834         }
3835
3836         // Channel should still work fine...
3837         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3838         let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3839         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3840 }
3841
3842 #[test]
3843 fn test_drop_messages_peer_disconnect_a() {
3844         do_test_drop_messages_peer_disconnect(0, true);
3845         do_test_drop_messages_peer_disconnect(0, false);
3846         do_test_drop_messages_peer_disconnect(1, false);
3847         do_test_drop_messages_peer_disconnect(2, false);
3848 }
3849
3850 #[test]
3851 fn test_drop_messages_peer_disconnect_b() {
3852         do_test_drop_messages_peer_disconnect(3, false);
3853         do_test_drop_messages_peer_disconnect(4, false);
3854         do_test_drop_messages_peer_disconnect(5, false);
3855         do_test_drop_messages_peer_disconnect(6, false);
3856 }
3857
3858 #[test]
3859 fn test_funding_peer_disconnect() {
3860         // Test that we can lock in our funding tx while disconnected
3861         let chanmon_cfgs = create_chanmon_cfgs(2);
3862         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3863         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3864         let persister: test_utils::TestPersister;
3865         let new_chain_monitor: test_utils::TestChainMonitor;
3866         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
3867         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3868         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3869
3870         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3871         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3872
3873         confirm_transaction(&nodes[0], &tx);
3874         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3875         assert!(events_1.is_empty());
3876
3877         reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3878
3879         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3880         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3881
3882         confirm_transaction(&nodes[1], &tx);
3883         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3884         assert!(events_2.is_empty());
3885
3886         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
3887         let as_reestablish = get_chan_reestablish_msgs!(nodes[0], nodes[1]).pop().unwrap();
3888         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
3889         let bs_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]).pop().unwrap();
3890
3891         // nodes[0] hasn't yet received a channel_ready, so it only sends that on reconnect.
3892         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
3893         let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3894         assert_eq!(events_3.len(), 1);
3895         let as_channel_ready = match events_3[0] {
3896                 MessageSendEvent::SendChannelReady { ref node_id, ref msg } => {
3897                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3898                         msg.clone()
3899                 },
3900                 _ => panic!("Unexpected event {:?}", events_3[0]),
3901         };
3902
3903         // nodes[1] received nodes[0]'s channel_ready on the first reconnect above, so it should send
3904         // announcement_signatures as well as channel_update.
3905         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reestablish);
3906         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3907         assert_eq!(events_4.len(), 3);
3908         let chan_id;
3909         let bs_channel_ready = match events_4[0] {
3910                 MessageSendEvent::SendChannelReady { ref node_id, ref msg } => {
3911                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3912                         chan_id = msg.channel_id;
3913                         msg.clone()
3914                 },
3915                 _ => panic!("Unexpected event {:?}", events_4[0]),
3916         };
3917         let bs_announcement_sigs = match events_4[1] {
3918                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3919                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3920                         msg.clone()
3921                 },
3922                 _ => panic!("Unexpected event {:?}", events_4[1]),
3923         };
3924         match events_4[2] {
3925                 MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } => {
3926                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3927                 },
3928                 _ => panic!("Unexpected event {:?}", events_4[2]),
3929         }
3930
3931         // Re-deliver nodes[0]'s channel_ready, which nodes[1] can safely ignore. It currently
3932         // generates a duplicative private channel_update
3933         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
3934         let events_5 = nodes[1].node.get_and_clear_pending_msg_events();
3935         assert_eq!(events_5.len(), 1);
3936         match events_5[0] {
3937                 MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } => {
3938                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3939                 },
3940                 _ => panic!("Unexpected event {:?}", events_5[0]),
3941         };
3942
3943         // When we deliver nodes[1]'s channel_ready, however, nodes[0] will generate its
3944         // announcement_signatures.
3945         nodes[0].node.handle_channel_ready(&nodes[1].node.get_our_node_id(), &bs_channel_ready);
3946         let events_6 = nodes[0].node.get_and_clear_pending_msg_events();
3947         assert_eq!(events_6.len(), 1);
3948         let as_announcement_sigs = match events_6[0] {
3949                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3950                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3951                         msg.clone()
3952                 },
3953                 _ => panic!("Unexpected event {:?}", events_6[0]),
3954         };
3955
3956         // When we deliver nodes[1]'s announcement_signatures to nodes[0], nodes[0] should immediately
3957         // broadcast the channel announcement globally, as well as re-send its (now-public)
3958         // channel_update.
3959         nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3960         let events_7 = nodes[0].node.get_and_clear_pending_msg_events();
3961         assert_eq!(events_7.len(), 1);
3962         let (chan_announcement, as_update) = match events_7[0] {
3963                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3964                         (msg.clone(), update_msg.clone())
3965                 },
3966                 _ => panic!("Unexpected event {:?}", events_7[0]),
3967         };
3968
3969         // Finally, deliver nodes[0]'s announcement_signatures to nodes[1] and make sure it creates the
3970         // same channel_announcement.
3971         nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3972         let events_8 = nodes[1].node.get_and_clear_pending_msg_events();
3973         assert_eq!(events_8.len(), 1);
3974         let bs_update = match events_8[0] {
3975                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3976                         assert_eq!(*msg, chan_announcement);
3977                         update_msg.clone()
3978                 },
3979                 _ => panic!("Unexpected event {:?}", events_8[0]),
3980         };
3981
3982         // Provide the channel announcement and public updates to the network graph
3983         nodes[0].gossip_sync.handle_channel_announcement(&chan_announcement).unwrap();
3984         nodes[0].gossip_sync.handle_channel_update(&bs_update).unwrap();
3985         nodes[0].gossip_sync.handle_channel_update(&as_update).unwrap();
3986
3987         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3988         let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3989         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
3990
3991         // Check that after deserialization and reconnection we can still generate an identical
3992         // channel_announcement from the cached signatures.
3993         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3994
3995         let nodes_0_serialized = nodes[0].node.encode();
3996         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
3997         get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
3998
3999         persister = test_utils::TestPersister::new();
4000         let keys_manager = &chanmon_cfgs[0].keys_manager;
4001         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);
4002         nodes[0].chain_monitor = &new_chain_monitor;
4003         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4004         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4005                 &mut chan_0_monitor_read, keys_manager).unwrap();
4006         assert!(chan_0_monitor_read.is_empty());
4007
4008         let mut nodes_0_read = &nodes_0_serialized[..];
4009         let (_, nodes_0_deserialized_tmp) = {
4010                 let mut channel_monitors = HashMap::new();
4011                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4012                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4013                         default_config: UserConfig::default(),
4014                         keys_manager,
4015                         fee_estimator: node_cfgs[0].fee_estimator,
4016                         chain_monitor: nodes[0].chain_monitor,
4017                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4018                         logger: nodes[0].logger,
4019                         channel_monitors,
4020                 }).unwrap()
4021         };
4022         nodes_0_deserialized = nodes_0_deserialized_tmp;
4023         assert!(nodes_0_read.is_empty());
4024
4025         assert_eq!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor),
4026                 ChannelMonitorUpdateStatus::Completed);
4027         nodes[0].node = &nodes_0_deserialized;
4028         check_added_monitors!(nodes[0], 1);
4029
4030         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4031 }
4032
4033 #[test]
4034 fn test_channel_ready_without_best_block_updated() {
4035         // Previously, if we were offline when a funding transaction was locked in, and then we came
4036         // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
4037         // generate a channel_ready until a later best_block_updated. This tests that we generate the
4038         // channel_ready immediately instead.
4039         let chanmon_cfgs = create_chanmon_cfgs(2);
4040         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4041         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4042         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4043         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
4044
4045         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());
4046
4047         let conf_height = nodes[0].best_block_info().1 + 1;
4048         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
4049         let block_txn = [funding_tx];
4050         let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
4051         let conf_block_header = nodes[0].get_block_header(conf_height);
4052         nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
4053
4054         // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
4055         let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
4056         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
4057 }
4058
4059 #[test]
4060 fn test_drop_messages_peer_disconnect_dual_htlc() {
4061         // Test that we can handle reconnecting when both sides of a channel have pending
4062         // commitment_updates when we disconnect.
4063         let chanmon_cfgs = create_chanmon_cfgs(2);
4064         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4065         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4066         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4067         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4068
4069         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
4070
4071         // Now try to send a second payment which will fail to send
4072         let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
4073         nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
4074         check_added_monitors!(nodes[0], 1);
4075
4076         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
4077         assert_eq!(events_1.len(), 1);
4078         match events_1[0] {
4079                 MessageSendEvent::UpdateHTLCs { .. } => {},
4080                 _ => panic!("Unexpected event"),
4081         }
4082
4083         nodes[1].node.claim_funds(payment_preimage_1);
4084         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
4085         check_added_monitors!(nodes[1], 1);
4086
4087         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
4088         assert_eq!(events_2.len(), 1);
4089         match events_2[0] {
4090                 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 } } => {
4091                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
4092                         assert!(update_add_htlcs.is_empty());
4093                         assert_eq!(update_fulfill_htlcs.len(), 1);
4094                         assert!(update_fail_htlcs.is_empty());
4095                         assert!(update_fail_malformed_htlcs.is_empty());
4096                         assert!(update_fee.is_none());
4097
4098                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
4099                         let events_3 = nodes[0].node.get_and_clear_pending_events();
4100                         assert_eq!(events_3.len(), 1);
4101                         match events_3[0] {
4102                                 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4103                                         assert_eq!(*payment_preimage, payment_preimage_1);
4104                                         assert_eq!(*payment_hash, payment_hash_1);
4105                                 },
4106                                 _ => panic!("Unexpected event"),
4107                         }
4108
4109                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
4110                         let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4111                         // No commitment_signed so get_event_msg's assert(len == 1) passes
4112                         check_added_monitors!(nodes[0], 1);
4113                 },
4114                 _ => panic!("Unexpected event"),
4115         }
4116
4117         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
4118         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4119
4120         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
4121         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4122         assert_eq!(reestablish_1.len(), 1);
4123         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
4124         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4125         assert_eq!(reestablish_2.len(), 1);
4126
4127         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4128         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4129         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4130         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4131
4132         assert!(as_resp.0.is_none());
4133         assert!(bs_resp.0.is_none());
4134
4135         assert!(bs_resp.1.is_none());
4136         assert!(bs_resp.2.is_none());
4137
4138         assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4139
4140         assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4141         assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4142         assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4143         assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4144         assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4145         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4146         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4147         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4148         // No commitment_signed so get_event_msg's assert(len == 1) passes
4149         check_added_monitors!(nodes[1], 1);
4150
4151         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4152         let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4153         assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4154         assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4155         assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4156         assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4157         assert!(bs_second_commitment_signed.update_fee.is_none());
4158         check_added_monitors!(nodes[1], 1);
4159
4160         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4161         let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4162         assert!(as_commitment_signed.update_add_htlcs.is_empty());
4163         assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4164         assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4165         assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4166         assert!(as_commitment_signed.update_fee.is_none());
4167         check_added_monitors!(nodes[0], 1);
4168
4169         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4170         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4171         // No commitment_signed so get_event_msg's assert(len == 1) passes
4172         check_added_monitors!(nodes[0], 1);
4173
4174         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4175         let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4176         // No commitment_signed so get_event_msg's assert(len == 1) passes
4177         check_added_monitors!(nodes[1], 1);
4178
4179         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4180         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4181         check_added_monitors!(nodes[1], 1);
4182
4183         expect_pending_htlcs_forwardable!(nodes[1]);
4184
4185         let events_5 = nodes[1].node.get_and_clear_pending_events();
4186         assert_eq!(events_5.len(), 1);
4187         match events_5[0] {
4188                 Event::PaymentReceived { ref payment_hash, ref purpose, .. } => {
4189                         assert_eq!(payment_hash_2, *payment_hash);
4190                         match &purpose {
4191                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4192                                         assert!(payment_preimage.is_none());
4193                                         assert_eq!(payment_secret_2, *payment_secret);
4194                                 },
4195                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
4196                         }
4197                 },
4198                 _ => panic!("Unexpected event"),
4199         }
4200
4201         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4202         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4203         check_added_monitors!(nodes[0], 1);
4204
4205         expect_payment_path_successful!(nodes[0]);
4206         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4207 }
4208
4209 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4210         // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4211         // to avoid our counterparty failing the channel.
4212         let chanmon_cfgs = create_chanmon_cfgs(2);
4213         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4214         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4215         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4216
4217         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4218
4219         let our_payment_hash = if send_partial_mpp {
4220                 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4221                 // Use the utility function send_payment_along_path to send the payment with MPP data which
4222                 // indicates there are more HTLCs coming.
4223                 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.
4224                 let payment_id = PaymentId([42; 32]);
4225                 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash, Some(payment_secret), payment_id, &route).unwrap();
4226                 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();
4227                 check_added_monitors!(nodes[0], 1);
4228                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4229                 assert_eq!(events.len(), 1);
4230                 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4231                 // hop should *not* yet generate any PaymentReceived event(s).
4232                 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4233                 our_payment_hash
4234         } else {
4235                 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4236         };
4237
4238         let mut block = Block {
4239                 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
4240                 txdata: vec![],
4241         };
4242         connect_block(&nodes[0], &block);
4243         connect_block(&nodes[1], &block);
4244         let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4245         for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4246                 block.header.prev_blockhash = block.block_hash();
4247                 connect_block(&nodes[0], &block);
4248                 connect_block(&nodes[1], &block);
4249         }
4250
4251         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
4252
4253         check_added_monitors!(nodes[1], 1);
4254         let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4255         assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4256         assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4257         assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4258         assert!(htlc_timeout_updates.update_fee.is_none());
4259
4260         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4261         commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4262         // 100_000 msat as u64, followed by the height at which we failed back above
4263         let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
4264         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(block_count - 1));
4265         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4266 }
4267
4268 #[test]
4269 fn test_htlc_timeout() {
4270         do_test_htlc_timeout(true);
4271         do_test_htlc_timeout(false);
4272 }
4273
4274 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4275         // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4276         let chanmon_cfgs = create_chanmon_cfgs(3);
4277         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4278         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4279         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4280         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4281         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4282
4283         // Make sure all nodes are at the same starting height
4284         connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4285         connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4286         connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4287
4288         // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4289         let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4290         {
4291                 nodes[1].node.send_payment(&route, first_payment_hash, &Some(first_payment_secret), PaymentId(first_payment_hash.0)).unwrap();
4292         }
4293         assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4294         check_added_monitors!(nodes[1], 1);
4295
4296         // Now attempt to route a second payment, which should be placed in the holding cell
4297         let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4298         let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4299         sending_node.node.send_payment(&route, second_payment_hash, &Some(second_payment_secret), PaymentId(second_payment_hash.0)).unwrap();
4300         if forwarded_htlc {
4301                 check_added_monitors!(nodes[0], 1);
4302                 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4303                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4304                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4305                 expect_pending_htlcs_forwardable!(nodes[1]);
4306         }
4307         check_added_monitors!(nodes[1], 0);
4308
4309         connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4310         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4311         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4312         connect_blocks(&nodes[1], 1);
4313
4314         if forwarded_htlc {
4315                 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 }]);
4316                 check_added_monitors!(nodes[1], 1);
4317                 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4318                 assert_eq!(fail_commit.len(), 1);
4319                 match fail_commit[0] {
4320                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4321                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4322                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4323                         },
4324                         _ => unreachable!(),
4325                 }
4326                 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4327         } else {
4328                 let events = nodes[1].node.get_and_clear_pending_events();
4329                 assert_eq!(events.len(), 2);
4330                 if let Event::PaymentPathFailed { ref payment_hash, .. } = events[0] {
4331                         assert_eq!(*payment_hash, second_payment_hash);
4332                 } else { panic!("Unexpected event"); }
4333                 if let Event::PaymentFailed { ref payment_hash, .. } = events[1] {
4334                         assert_eq!(*payment_hash, second_payment_hash);
4335                 } else { panic!("Unexpected event"); }
4336         }
4337 }
4338
4339 #[test]
4340 fn test_holding_cell_htlc_add_timeouts() {
4341         do_test_holding_cell_htlc_add_timeouts(false);
4342         do_test_holding_cell_htlc_add_timeouts(true);
4343 }
4344
4345 #[test]
4346 fn test_no_txn_manager_serialize_deserialize() {
4347         let chanmon_cfgs = create_chanmon_cfgs(2);
4348         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4349         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4350         let logger: test_utils::TestLogger;
4351         let fee_estimator: test_utils::TestFeeEstimator;
4352         let persister: test_utils::TestPersister;
4353         let new_chain_monitor: test_utils::TestChainMonitor;
4354         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4355         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4356
4357         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4358
4359         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4360
4361         let nodes_0_serialized = nodes[0].node.encode();
4362         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4363         get_monitor!(nodes[0], OutPoint { txid: tx.txid(), index: 0 }.to_channel_id())
4364                 .write(&mut chan_0_monitor_serialized).unwrap();
4365
4366         logger = test_utils::TestLogger::new();
4367         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4368         persister = test_utils::TestPersister::new();
4369         let keys_manager = &chanmon_cfgs[0].keys_manager;
4370         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4371         nodes[0].chain_monitor = &new_chain_monitor;
4372         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4373         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4374                 &mut chan_0_monitor_read, keys_manager).unwrap();
4375         assert!(chan_0_monitor_read.is_empty());
4376
4377         let mut nodes_0_read = &nodes_0_serialized[..];
4378         let config = UserConfig::default();
4379         let (_, nodes_0_deserialized_tmp) = {
4380                 let mut channel_monitors = HashMap::new();
4381                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4382                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4383                         default_config: config,
4384                         keys_manager,
4385                         fee_estimator: &fee_estimator,
4386                         chain_monitor: nodes[0].chain_monitor,
4387                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4388                         logger: &logger,
4389                         channel_monitors,
4390                 }).unwrap()
4391         };
4392         nodes_0_deserialized = nodes_0_deserialized_tmp;
4393         assert!(nodes_0_read.is_empty());
4394
4395         assert_eq!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor),
4396                 ChannelMonitorUpdateStatus::Completed);
4397         nodes[0].node = &nodes_0_deserialized;
4398         assert_eq!(nodes[0].node.list_channels().len(), 1);
4399         check_added_monitors!(nodes[0], 1);
4400
4401         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
4402         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4403         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
4404         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4405
4406         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4407         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4408         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4409         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4410
4411         let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4412         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
4413         for node in nodes.iter() {
4414                 assert!(node.gossip_sync.handle_channel_announcement(&announcement).unwrap());
4415                 node.gossip_sync.handle_channel_update(&as_update).unwrap();
4416                 node.gossip_sync.handle_channel_update(&bs_update).unwrap();
4417         }
4418
4419         send_payment(&nodes[0], &[&nodes[1]], 1000000);
4420 }
4421
4422 #[test]
4423 fn test_manager_serialize_deserialize_events() {
4424         // This test makes sure the events field in ChannelManager survives de/serialization
4425         let chanmon_cfgs = create_chanmon_cfgs(2);
4426         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4427         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4428         let fee_estimator: test_utils::TestFeeEstimator;
4429         let persister: test_utils::TestPersister;
4430         let logger: test_utils::TestLogger;
4431         let new_chain_monitor: test_utils::TestChainMonitor;
4432         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4433         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4434
4435         // Start creating a channel, but stop right before broadcasting the funding transaction
4436         let channel_value = 100000;
4437         let push_msat = 10001;
4438         let a_flags = channelmanager::provided_init_features();
4439         let b_flags = channelmanager::provided_init_features();
4440         let node_a = nodes.remove(0);
4441         let node_b = nodes.remove(0);
4442         node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
4443         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()));
4444         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()));
4445
4446         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, &node_b.node.get_our_node_id(), channel_value, 42);
4447
4448         node_a.node.funding_transaction_generated(&temporary_channel_id, &node_b.node.get_our_node_id(), tx.clone()).unwrap();
4449         check_added_monitors!(node_a, 0);
4450
4451         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()));
4452         {
4453                 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
4454                 assert_eq!(added_monitors.len(), 1);
4455                 assert_eq!(added_monitors[0].0, funding_output);
4456                 added_monitors.clear();
4457         }
4458
4459         let bs_funding_signed = get_event_msg!(node_b, MessageSendEvent::SendFundingSigned, node_a.node.get_our_node_id());
4460         node_a.node.handle_funding_signed(&node_b.node.get_our_node_id(), &bs_funding_signed);
4461         {
4462                 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
4463                 assert_eq!(added_monitors.len(), 1);
4464                 assert_eq!(added_monitors[0].0, funding_output);
4465                 added_monitors.clear();
4466         }
4467         // Normally, this is where node_a would broadcast the funding transaction, but the test de/serializes first instead
4468
4469         nodes.push(node_a);
4470         nodes.push(node_b);
4471
4472         // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4473         let nodes_0_serialized = nodes[0].node.encode();
4474         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4475         get_monitor!(nodes[0], bs_funding_signed.channel_id).write(&mut chan_0_monitor_serialized).unwrap();
4476
4477         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4478         logger = test_utils::TestLogger::new();
4479         persister = test_utils::TestPersister::new();
4480         let keys_manager = &chanmon_cfgs[0].keys_manager;
4481         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4482         nodes[0].chain_monitor = &new_chain_monitor;
4483         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4484         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4485                 &mut chan_0_monitor_read, keys_manager).unwrap();
4486         assert!(chan_0_monitor_read.is_empty());
4487
4488         let mut nodes_0_read = &nodes_0_serialized[..];
4489         let config = UserConfig::default();
4490         let (_, nodes_0_deserialized_tmp) = {
4491                 let mut channel_monitors = HashMap::new();
4492                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4493                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4494                         default_config: config,
4495                         keys_manager,
4496                         fee_estimator: &fee_estimator,
4497                         chain_monitor: nodes[0].chain_monitor,
4498                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4499                         logger: &logger,
4500                         channel_monitors,
4501                 }).unwrap()
4502         };
4503         nodes_0_deserialized = nodes_0_deserialized_tmp;
4504         assert!(nodes_0_read.is_empty());
4505
4506         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4507
4508         assert_eq!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor),
4509                 ChannelMonitorUpdateStatus::Completed);
4510         nodes[0].node = &nodes_0_deserialized;
4511
4512         // After deserializing, make sure the funding_transaction is still held by the channel manager
4513         let events_4 = nodes[0].node.get_and_clear_pending_events();
4514         assert_eq!(events_4.len(), 0);
4515         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
4516         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
4517
4518         // Make sure the channel is functioning as though the de/serialization never happened
4519         assert_eq!(nodes[0].node.list_channels().len(), 1);
4520         check_added_monitors!(nodes[0], 1);
4521
4522         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
4523         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4524         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
4525         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4526
4527         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4528         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4529         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4530         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4531
4532         let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4533         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
4534         for node in nodes.iter() {
4535                 assert!(node.gossip_sync.handle_channel_announcement(&announcement).unwrap());
4536                 node.gossip_sync.handle_channel_update(&as_update).unwrap();
4537                 node.gossip_sync.handle_channel_update(&bs_update).unwrap();
4538         }
4539
4540         send_payment(&nodes[0], &[&nodes[1]], 1000000);
4541 }
4542
4543 #[test]
4544 fn test_simple_manager_serialize_deserialize() {
4545         let chanmon_cfgs = create_chanmon_cfgs(2);
4546         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4547         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4548         let logger: test_utils::TestLogger;
4549         let fee_estimator: test_utils::TestFeeEstimator;
4550         let persister: test_utils::TestPersister;
4551         let new_chain_monitor: test_utils::TestChainMonitor;
4552         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4553         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4554         let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
4555
4556         let (our_payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4557         let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4558
4559         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4560
4561         let nodes_0_serialized = nodes[0].node.encode();
4562         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4563         get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
4564
4565         logger = test_utils::TestLogger::new();
4566         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4567         persister = test_utils::TestPersister::new();
4568         let keys_manager = &chanmon_cfgs[0].keys_manager;
4569         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4570         nodes[0].chain_monitor = &new_chain_monitor;
4571         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4572         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4573                 &mut chan_0_monitor_read, keys_manager).unwrap();
4574         assert!(chan_0_monitor_read.is_empty());
4575
4576         let mut nodes_0_read = &nodes_0_serialized[..];
4577         let (_, nodes_0_deserialized_tmp) = {
4578                 let mut channel_monitors = HashMap::new();
4579                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4580                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4581                         default_config: UserConfig::default(),
4582                         keys_manager,
4583                         fee_estimator: &fee_estimator,
4584                         chain_monitor: nodes[0].chain_monitor,
4585                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4586                         logger: &logger,
4587                         channel_monitors,
4588                 }).unwrap()
4589         };
4590         nodes_0_deserialized = nodes_0_deserialized_tmp;
4591         assert!(nodes_0_read.is_empty());
4592
4593         assert_eq!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor),
4594                 ChannelMonitorUpdateStatus::Completed);
4595         nodes[0].node = &nodes_0_deserialized;
4596         check_added_monitors!(nodes[0], 1);
4597
4598         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4599
4600         fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4601         claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
4602 }
4603
4604 #[test]
4605 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4606         // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4607         let chanmon_cfgs = create_chanmon_cfgs(4);
4608         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4609         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4610         let logger: test_utils::TestLogger;
4611         let fee_estimator: test_utils::TestFeeEstimator;
4612         let persister: test_utils::TestPersister;
4613         let new_chain_monitor: test_utils::TestChainMonitor;
4614         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4615         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4616         let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
4617         let chan_id_2 = create_announced_chan_between_nodes(&nodes, 2, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
4618         let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4619
4620         let mut node_0_stale_monitors_serialized = Vec::new();
4621         for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4622                 let mut writer = test_utils::TestVecWriter(Vec::new());
4623                 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4624                 node_0_stale_monitors_serialized.push(writer.0);
4625         }
4626
4627         let (our_payment_preimage, _, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4628
4629         // Serialize the ChannelManager here, but the monitor we keep up-to-date
4630         let nodes_0_serialized = nodes[0].node.encode();
4631
4632         route_payment(&nodes[0], &[&nodes[3]], 1000000);
4633         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4634         nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4635         nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4636
4637         // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4638         // nodes[3])
4639         let mut node_0_monitors_serialized = Vec::new();
4640         for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4641                 let mut writer = test_utils::TestVecWriter(Vec::new());
4642                 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4643                 node_0_monitors_serialized.push(writer.0);
4644         }
4645
4646         logger = test_utils::TestLogger::new();
4647         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4648         persister = test_utils::TestPersister::new();
4649         let keys_manager = &chanmon_cfgs[0].keys_manager;
4650         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4651         nodes[0].chain_monitor = &new_chain_monitor;
4652
4653
4654         let mut node_0_stale_monitors = Vec::new();
4655         for serialized in node_0_stale_monitors_serialized.iter() {
4656                 let mut read = &serialized[..];
4657                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4658                 assert!(read.is_empty());
4659                 node_0_stale_monitors.push(monitor);
4660         }
4661
4662         let mut node_0_monitors = Vec::new();
4663         for serialized in node_0_monitors_serialized.iter() {
4664                 let mut read = &serialized[..];
4665                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4666                 assert!(read.is_empty());
4667                 node_0_monitors.push(monitor);
4668         }
4669
4670         let mut nodes_0_read = &nodes_0_serialized[..];
4671         if let Err(msgs::DecodeError::InvalidValue) =
4672                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4673                 default_config: UserConfig::default(),
4674                 keys_manager,
4675                 fee_estimator: &fee_estimator,
4676                 chain_monitor: nodes[0].chain_monitor,
4677                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4678                 logger: &logger,
4679                 channel_monitors: node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4680         }) { } else {
4681                 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4682         };
4683
4684         let mut nodes_0_read = &nodes_0_serialized[..];
4685         let (_, nodes_0_deserialized_tmp) =
4686                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4687                 default_config: UserConfig::default(),
4688                 keys_manager,
4689                 fee_estimator: &fee_estimator,
4690                 chain_monitor: nodes[0].chain_monitor,
4691                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4692                 logger: &logger,
4693                 channel_monitors: node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4694         }).unwrap();
4695         nodes_0_deserialized = nodes_0_deserialized_tmp;
4696         assert!(nodes_0_read.is_empty());
4697
4698         { // Channel close should result in a commitment tx
4699                 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4700                 assert_eq!(txn.len(), 1);
4701                 check_spends!(txn[0], funding_tx);
4702                 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4703         }
4704
4705         for monitor in node_0_monitors.drain(..) {
4706                 assert_eq!(nodes[0].chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor),
4707                         ChannelMonitorUpdateStatus::Completed);
4708                 check_added_monitors!(nodes[0], 1);
4709         }
4710         nodes[0].node = &nodes_0_deserialized;
4711         check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
4712
4713         // nodes[1] and nodes[2] have no lost state with nodes[0]...
4714         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4715         reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4716         //... and we can even still claim the payment!
4717         claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage);
4718
4719         nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
4720         let reestablish = get_chan_reestablish_msgs!(nodes[3], nodes[0]).pop().unwrap();
4721         nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
4722         nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4723         let mut found_err = false;
4724         for msg_event in nodes[0].node.get_and_clear_pending_msg_events() {
4725                 if let MessageSendEvent::HandleError { ref action, .. } = msg_event {
4726                         match action {
4727                                 &ErrorAction::SendErrorMessage { ref msg } => {
4728                                         assert_eq!(msg.channel_id, channel_id);
4729                                         assert!(!found_err);
4730                                         found_err = true;
4731                                 },
4732                                 _ => panic!("Unexpected event!"),
4733                         }
4734                 }
4735         }
4736         assert!(found_err);
4737 }
4738
4739 macro_rules! check_spendable_outputs {
4740         ($node: expr, $keysinterface: expr) => {
4741                 {
4742                         let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4743                         let mut txn = Vec::new();
4744                         let mut all_outputs = Vec::new();
4745                         let secp_ctx = Secp256k1::new();
4746                         for event in events.drain(..) {
4747                                 match event {
4748                                         Event::SpendableOutputs { mut outputs } => {
4749                                                 for outp in outputs.drain(..) {
4750                                                         txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4751                                                         all_outputs.push(outp);
4752                                                 }
4753                                         },
4754                                         _ => panic!("Unexpected event"),
4755                                 };
4756                         }
4757                         if all_outputs.len() > 1 {
4758                                 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) {
4759                                         txn.push(tx);
4760                                 }
4761                         }
4762                         txn
4763                 }
4764         }
4765 }
4766
4767 #[test]
4768 fn test_claim_sizeable_push_msat() {
4769         // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4770         let chanmon_cfgs = create_chanmon_cfgs(2);
4771         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4772         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4773         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4774
4775         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());
4776         nodes[1].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
4777         check_closed_broadcast!(nodes[1], true);
4778         check_added_monitors!(nodes[1], 1);
4779         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4780         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4781         assert_eq!(node_txn.len(), 1);
4782         check_spends!(node_txn[0], chan.3);
4783         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
4784
4785         mine_transaction(&nodes[1], &node_txn[0]);
4786         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4787
4788         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4789         assert_eq!(spend_txn.len(), 1);
4790         assert_eq!(spend_txn[0].input.len(), 1);
4791         check_spends!(spend_txn[0], node_txn[0]);
4792         assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4793 }
4794
4795 #[test]
4796 fn test_claim_on_remote_sizeable_push_msat() {
4797         // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4798         // to_remote output is encumbered by a P2WPKH
4799         let chanmon_cfgs = create_chanmon_cfgs(2);
4800         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4801         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4802         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4803
4804         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());
4805         nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
4806         check_closed_broadcast!(nodes[0], true);
4807         check_added_monitors!(nodes[0], 1);
4808         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4809
4810         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4811         assert_eq!(node_txn.len(), 1);
4812         check_spends!(node_txn[0], chan.3);
4813         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
4814
4815         mine_transaction(&nodes[1], &node_txn[0]);
4816         check_closed_broadcast!(nodes[1], true);
4817         check_added_monitors!(nodes[1], 1);
4818         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4819         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4820
4821         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4822         assert_eq!(spend_txn.len(), 1);
4823         check_spends!(spend_txn[0], node_txn[0]);
4824 }
4825
4826 #[test]
4827 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4828         // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4829         // to_remote output is encumbered by a P2WPKH
4830
4831         let chanmon_cfgs = create_chanmon_cfgs(2);
4832         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4833         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4834         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4835
4836         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4837         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4838         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4839         assert_eq!(revoked_local_txn[0].input.len(), 1);
4840         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4841
4842         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4843         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4844         check_closed_broadcast!(nodes[1], true);
4845         check_added_monitors!(nodes[1], 1);
4846         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4847
4848         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4849         mine_transaction(&nodes[1], &node_txn[0]);
4850         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4851
4852         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4853         assert_eq!(spend_txn.len(), 3);
4854         check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4855         check_spends!(spend_txn[1], node_txn[0]);
4856         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4857 }
4858
4859 #[test]
4860 fn test_static_spendable_outputs_preimage_tx() {
4861         let chanmon_cfgs = create_chanmon_cfgs(2);
4862         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4863         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4864         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4865
4866         // Create some initial channels
4867         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4868
4869         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
4870
4871         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4872         assert_eq!(commitment_tx[0].input.len(), 1);
4873         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4874
4875         // Settle A's commitment tx on B's chain
4876         nodes[1].node.claim_funds(payment_preimage);
4877         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
4878         check_added_monitors!(nodes[1], 1);
4879         mine_transaction(&nodes[1], &commitment_tx[0]);
4880         check_added_monitors!(nodes[1], 1);
4881         let events = nodes[1].node.get_and_clear_pending_msg_events();
4882         match events[0] {
4883                 MessageSendEvent::UpdateHTLCs { .. } => {},
4884                 _ => panic!("Unexpected event"),
4885         }
4886         match events[1] {
4887                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4888                 _ => panic!("Unexepected event"),
4889         }
4890
4891         // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4892         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4893         assert_eq!(node_txn.len(), 3);
4894         check_spends!(node_txn[0], commitment_tx[0]);
4895         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4896         check_spends!(node_txn[1], chan_1.3);
4897         check_spends!(node_txn[2], node_txn[1]);
4898
4899         mine_transaction(&nodes[1], &node_txn[0]);
4900         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4901         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4902
4903         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4904         assert_eq!(spend_txn.len(), 1);
4905         check_spends!(spend_txn[0], node_txn[0]);
4906 }
4907
4908 #[test]
4909 fn test_static_spendable_outputs_timeout_tx() {
4910         let chanmon_cfgs = create_chanmon_cfgs(2);
4911         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4912         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4913         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4914
4915         // Create some initial channels
4916         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4917
4918         // Rebalance the network a bit by relaying one payment through all the channels ...
4919         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4920
4921         let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4922
4923         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4924         assert_eq!(commitment_tx[0].input.len(), 1);
4925         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4926
4927         // Settle A's commitment tx on B' chain
4928         mine_transaction(&nodes[1], &commitment_tx[0]);
4929         check_added_monitors!(nodes[1], 1);
4930         let events = nodes[1].node.get_and_clear_pending_msg_events();
4931         match events[0] {
4932                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4933                 _ => panic!("Unexpected event"),
4934         }
4935         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4936
4937         // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4938         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4939         assert_eq!(node_txn.len(), 2); // ChannelManager : 1 local commitent tx, ChannelMonitor: timeout tx
4940         check_spends!(node_txn[0], chan_1.3.clone());
4941         check_spends!(node_txn[1],  commitment_tx[0].clone());
4942         assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4943
4944         mine_transaction(&nodes[1], &node_txn[1]);
4945         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4946         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4947         expect_payment_failed!(nodes[1], our_payment_hash, false);
4948
4949         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4950         assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4951         check_spends!(spend_txn[0], commitment_tx[0]);
4952         check_spends!(spend_txn[1], node_txn[1]);
4953         check_spends!(spend_txn[2], node_txn[1], commitment_tx[0]); // All outputs
4954 }
4955
4956 #[test]
4957 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4958         let chanmon_cfgs = create_chanmon_cfgs(2);
4959         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4960         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4961         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4962
4963         // Create some initial channels
4964         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4965
4966         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4967         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4968         assert_eq!(revoked_local_txn[0].input.len(), 1);
4969         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4970
4971         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4972
4973         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4974         check_closed_broadcast!(nodes[1], true);
4975         check_added_monitors!(nodes[1], 1);
4976         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4977
4978         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4979         assert_eq!(node_txn.len(), 2);
4980         assert_eq!(node_txn[0].input.len(), 2);
4981         check_spends!(node_txn[0], revoked_local_txn[0]);
4982
4983         mine_transaction(&nodes[1], &node_txn[0]);
4984         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4985
4986         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4987         assert_eq!(spend_txn.len(), 1);
4988         check_spends!(spend_txn[0], node_txn[0]);
4989 }
4990
4991 #[test]
4992 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4993         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4994         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4995         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4996         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4997         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4998
4999         // Create some initial channels
5000         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5001
5002         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5003         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5004         assert_eq!(revoked_local_txn[0].input.len(), 1);
5005         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5006
5007         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
5008
5009         // A will generate HTLC-Timeout from revoked commitment tx
5010         mine_transaction(&nodes[0], &revoked_local_txn[0]);
5011         check_closed_broadcast!(nodes[0], true);
5012         check_added_monitors!(nodes[0], 1);
5013         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5014         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5015
5016         let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
5017         assert_eq!(revoked_htlc_txn.len(), 2);
5018         check_spends!(revoked_htlc_txn[0], chan_1.3);
5019         assert_eq!(revoked_htlc_txn[1].input.len(), 1);
5020         assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5021         check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
5022         assert_ne!(revoked_htlc_txn[1].lock_time.0, 0); // HTLC-Timeout
5023
5024         // B will generate justice tx from A's revoked commitment/HTLC tx
5025         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
5026         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[1].clone()] });
5027         check_closed_broadcast!(nodes[1], true);
5028         check_added_monitors!(nodes[1], 1);
5029         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5030
5031         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5032         assert_eq!(node_txn.len(), 3); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs, ChannelManager: local commitment tx
5033         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5034         // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
5035         // transactions next...
5036         assert_eq!(node_txn[0].input.len(), 3);
5037         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[1]);
5038
5039         assert_eq!(node_txn[1].input.len(), 2);
5040         check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[1]);
5041         if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[1].txid() {
5042                 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
5043         } else {
5044                 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[1].txid());
5045                 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[1].input[0].previous_output);
5046         }
5047
5048         assert_eq!(node_txn[2].input.len(), 1);
5049         check_spends!(node_txn[2], chan_1.3);
5050
5051         mine_transaction(&nodes[1], &node_txn[1]);
5052         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5053
5054         // Check B's ChannelMonitor was able to generate the right spendable output descriptor
5055         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5056         assert_eq!(spend_txn.len(), 1);
5057         assert_eq!(spend_txn[0].input.len(), 1);
5058         check_spends!(spend_txn[0], node_txn[1]);
5059 }
5060
5061 #[test]
5062 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
5063         let mut chanmon_cfgs = create_chanmon_cfgs(2);
5064         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
5065         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5066         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5067         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5068
5069         // Create some initial channels
5070         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5071
5072         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5073         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5074         assert_eq!(revoked_local_txn[0].input.len(), 1);
5075         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5076
5077         // The to-be-revoked commitment tx should have one HTLC and one to_remote output
5078         assert_eq!(revoked_local_txn[0].output.len(), 2);
5079
5080         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
5081
5082         // B will generate HTLC-Success from revoked commitment tx
5083         mine_transaction(&nodes[1], &revoked_local_txn[0]);
5084         check_closed_broadcast!(nodes[1], true);
5085         check_added_monitors!(nodes[1], 1);
5086         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5087         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5088
5089         assert_eq!(revoked_htlc_txn.len(), 2);
5090         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
5091         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5092         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
5093
5094         // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
5095         let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
5096         assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
5097
5098         // A will generate justice tx from B's revoked commitment/HTLC tx
5099         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
5100         connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
5101         check_closed_broadcast!(nodes[0], true);
5102         check_added_monitors!(nodes[0], 1);
5103         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5104
5105         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5106         assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
5107
5108         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5109         // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
5110         // transactions next...
5111         assert_eq!(node_txn[0].input.len(), 2);
5112         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
5113         if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
5114                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5115         } else {
5116                 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
5117                 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5118         }
5119
5120         assert_eq!(node_txn[1].input.len(), 1);
5121         check_spends!(node_txn[1], revoked_htlc_txn[0]);
5122
5123         check_spends!(node_txn[2], chan_1.3);
5124
5125         mine_transaction(&nodes[0], &node_txn[1]);
5126         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5127
5128         // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
5129         // didn't try to generate any new transactions.
5130
5131         // Check A's ChannelMonitor was able to generate the right spendable output descriptor
5132         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5133         assert_eq!(spend_txn.len(), 3);
5134         assert_eq!(spend_txn[0].input.len(), 1);
5135         check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
5136         assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5137         check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
5138         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
5139 }
5140
5141 #[test]
5142 fn test_onchain_to_onchain_claim() {
5143         // Test that in case of channel closure, we detect the state of output and claim HTLC
5144         // on downstream peer's remote commitment tx.
5145         // First, have C claim an HTLC against its own latest commitment transaction.
5146         // Then, broadcast these to B, which should update the monitor downstream on the A<->B
5147         // channel.
5148         // Finally, check that B will claim the HTLC output if A's latest commitment transaction
5149         // gets broadcast.
5150
5151         let chanmon_cfgs = create_chanmon_cfgs(3);
5152         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5153         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5154         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5155
5156         // Create some initial channels
5157         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5158         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5159
5160         // Ensure all nodes are at the same height
5161         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5162         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5163         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5164         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5165
5166         // Rebalance the network a bit by relaying one payment through all the channels ...
5167         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5168         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5169
5170         let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
5171         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
5172         check_spends!(commitment_tx[0], chan_2.3);
5173         nodes[2].node.claim_funds(payment_preimage);
5174         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
5175         check_added_monitors!(nodes[2], 1);
5176         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5177         assert!(updates.update_add_htlcs.is_empty());
5178         assert!(updates.update_fail_htlcs.is_empty());
5179         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5180         assert!(updates.update_fail_malformed_htlcs.is_empty());
5181
5182         mine_transaction(&nodes[2], &commitment_tx[0]);
5183         check_closed_broadcast!(nodes[2], true);
5184         check_added_monitors!(nodes[2], 1);
5185         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5186
5187         let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
5188         assert_eq!(c_txn.len(), 3);
5189         assert_eq!(c_txn[0], c_txn[2]);
5190         assert_eq!(commitment_tx[0], c_txn[1]);
5191         check_spends!(c_txn[1], chan_2.3);
5192         check_spends!(c_txn[2], c_txn[1]);
5193         assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
5194         assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5195         assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5196         assert_eq!(c_txn[0].lock_time.0, 0); // Success tx
5197
5198         // 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
5199         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
5200         connect_block(&nodes[1], &Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]});
5201         check_added_monitors!(nodes[1], 1);
5202         let events = nodes[1].node.get_and_clear_pending_events();
5203         assert_eq!(events.len(), 2);
5204         match events[0] {
5205                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5206                 _ => panic!("Unexpected event"),
5207         }
5208         match events[1] {
5209                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
5210                         assert_eq!(fee_earned_msat, Some(1000));
5211                         assert_eq!(prev_channel_id, Some(chan_1.2));
5212                         assert_eq!(claim_from_onchain_tx, true);
5213                         assert_eq!(next_channel_id, Some(chan_2.2));
5214                 },
5215                 _ => panic!("Unexpected event"),
5216         }
5217         {
5218                 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5219                 // ChannelMonitor: claim tx
5220                 assert_eq!(b_txn.len(), 1);
5221                 check_spends!(b_txn[0], chan_2.3); // B local commitment tx, issued by ChannelManager
5222                 b_txn.clear();
5223         }
5224         check_added_monitors!(nodes[1], 1);
5225         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5226         assert_eq!(msg_events.len(), 3);
5227         match msg_events[0] {
5228                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5229                 _ => panic!("Unexpected event"),
5230         }
5231         match msg_events[1] {
5232                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
5233                 _ => panic!("Unexpected event"),
5234         }
5235         match msg_events[2] {
5236                 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, .. } } => {
5237                         assert!(update_add_htlcs.is_empty());
5238                         assert!(update_fail_htlcs.is_empty());
5239                         assert_eq!(update_fulfill_htlcs.len(), 1);
5240                         assert!(update_fail_malformed_htlcs.is_empty());
5241                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5242                 },
5243                 _ => panic!("Unexpected event"),
5244         };
5245         // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
5246         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5247         mine_transaction(&nodes[1], &commitment_tx[0]);
5248         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5249         let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5250         // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
5251         assert_eq!(b_txn.len(), 3);
5252         check_spends!(b_txn[1], chan_1.3);
5253         check_spends!(b_txn[2], b_txn[1]);
5254         check_spends!(b_txn[0], commitment_tx[0]);
5255         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5256         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5257         assert_eq!(b_txn[0].lock_time.0, 0); // Success tx
5258
5259         check_closed_broadcast!(nodes[1], true);
5260         check_added_monitors!(nodes[1], 1);
5261 }
5262
5263 #[test]
5264 fn test_duplicate_payment_hash_one_failure_one_success() {
5265         // Topology : A --> B --> C --> D
5266         // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5267         // Note that because C will refuse to generate two payment secrets for the same payment hash,
5268         // we forward one of the payments onwards to D.
5269         let chanmon_cfgs = create_chanmon_cfgs(4);
5270         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
5271         // When this test was written, the default base fee floated based on the HTLC count.
5272         // It is now fixed, so we simply set the fee to the expected value here.
5273         let mut config = test_default_channel_config();
5274         config.channel_config.forwarding_fee_base_msat = 196;
5275         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
5276                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5277         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
5278
5279         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5280         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5281         create_announced_chan_between_nodes(&nodes, 2, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5282
5283         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5284         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5285         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5286         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5287         connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
5288
5289         let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 900_000);
5290
5291         let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200).unwrap();
5292         // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
5293         // script push size limit so that the below script length checks match
5294         // ACCEPTED_HTLC_SCRIPT_WEIGHT.
5295         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id())
5296                 .with_features(channelmanager::provided_invoice_features());
5297         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 900000, TEST_FINAL_CLTV - 40);
5298         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 900000, duplicate_payment_hash, payment_secret);
5299
5300         let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5301         assert_eq!(commitment_txn[0].input.len(), 1);
5302         check_spends!(commitment_txn[0], chan_2.3);
5303
5304         mine_transaction(&nodes[1], &commitment_txn[0]);
5305         check_closed_broadcast!(nodes[1], true);
5306         check_added_monitors!(nodes[1], 1);
5307         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5308         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
5309
5310         let htlc_timeout_tx;
5311         { // Extract one of the two HTLC-Timeout transaction
5312                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5313                 // ChannelMonitor: timeout tx * 2-or-3, ChannelManager: local commitment tx
5314                 assert!(node_txn.len() == 4 || node_txn.len() == 3);
5315                 check_spends!(node_txn[0], chan_2.3);
5316
5317                 check_spends!(node_txn[1], commitment_txn[0]);
5318                 assert_eq!(node_txn[1].input.len(), 1);
5319
5320                 if node_txn.len() > 3 {
5321                         check_spends!(node_txn[2], commitment_txn[0]);
5322                         assert_eq!(node_txn[2].input.len(), 1);
5323                         assert_eq!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
5324
5325                         check_spends!(node_txn[3], commitment_txn[0]);
5326                         assert_ne!(node_txn[1].input[0].previous_output, node_txn[3].input[0].previous_output);
5327                 } else {
5328                         check_spends!(node_txn[2], commitment_txn[0]);
5329                         assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
5330                 }
5331
5332                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5333                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5334                 if node_txn.len() > 3 {
5335                         assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5336                 }
5337                 htlc_timeout_tx = node_txn[1].clone();
5338         }
5339
5340         nodes[2].node.claim_funds(our_payment_preimage);
5341         expect_payment_claimed!(nodes[2], duplicate_payment_hash, 900_000);
5342
5343         mine_transaction(&nodes[2], &commitment_txn[0]);
5344         check_added_monitors!(nodes[2], 2);
5345         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5346         let events = nodes[2].node.get_and_clear_pending_msg_events();
5347         match events[0] {
5348                 MessageSendEvent::UpdateHTLCs { .. } => {},
5349                 _ => panic!("Unexpected event"),
5350         }
5351         match events[1] {
5352                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5353                 _ => panic!("Unexepected event"),
5354         }
5355         let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5356         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)
5357         check_spends!(htlc_success_txn[0], commitment_txn[0]);
5358         check_spends!(htlc_success_txn[1], commitment_txn[0]);
5359         assert_eq!(htlc_success_txn[0].input.len(), 1);
5360         assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5361         assert_eq!(htlc_success_txn[1].input.len(), 1);
5362         assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5363         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
5364         assert_eq!(htlc_success_txn[2], commitment_txn[0]);
5365         assert_eq!(htlc_success_txn[3], htlc_success_txn[0]);
5366         assert_eq!(htlc_success_txn[4], htlc_success_txn[1]);
5367         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
5368
5369         mine_transaction(&nodes[1], &htlc_timeout_tx);
5370         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5371         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 }]);
5372         let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5373         assert!(htlc_updates.update_add_htlcs.is_empty());
5374         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5375         let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
5376         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5377         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5378         check_added_monitors!(nodes[1], 1);
5379
5380         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5381         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5382         {
5383                 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5384         }
5385         expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
5386
5387         // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5388         // Note that the fee paid is effectively double as the HTLC value (including the nodes[1] fee
5389         // and nodes[2] fee) is rounded down and then claimed in full.
5390         mine_transaction(&nodes[1], &htlc_success_txn[0]);
5391         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196*2), true, true);
5392         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5393         assert!(updates.update_add_htlcs.is_empty());
5394         assert!(updates.update_fail_htlcs.is_empty());
5395         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5396         assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
5397         assert!(updates.update_fail_malformed_htlcs.is_empty());
5398         check_added_monitors!(nodes[1], 1);
5399
5400         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5401         commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5402
5403         let events = nodes[0].node.get_and_clear_pending_events();
5404         match events[0] {
5405                 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
5406                         assert_eq!(*payment_preimage, our_payment_preimage);
5407                         assert_eq!(*payment_hash, duplicate_payment_hash);
5408                 }
5409                 _ => panic!("Unexpected event"),
5410         }
5411 }
5412
5413 #[test]
5414 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5415         let chanmon_cfgs = create_chanmon_cfgs(2);
5416         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5417         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5418         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5419
5420         // Create some initial channels
5421         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5422
5423         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
5424         let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5425         assert_eq!(local_txn.len(), 1);
5426         assert_eq!(local_txn[0].input.len(), 1);
5427         check_spends!(local_txn[0], chan_1.3);
5428
5429         // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5430         nodes[1].node.claim_funds(payment_preimage);
5431         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
5432         check_added_monitors!(nodes[1], 1);
5433
5434         mine_transaction(&nodes[1], &local_txn[0]);
5435         check_added_monitors!(nodes[1], 1);
5436         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5437         let events = nodes[1].node.get_and_clear_pending_msg_events();
5438         match events[0] {
5439                 MessageSendEvent::UpdateHTLCs { .. } => {},
5440                 _ => panic!("Unexpected event"),
5441         }
5442         match events[1] {
5443                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5444                 _ => panic!("Unexepected event"),
5445         }
5446         let node_tx = {
5447                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5448                 assert_eq!(node_txn.len(), 3);
5449                 assert_eq!(node_txn[0], node_txn[2]);
5450                 assert_eq!(node_txn[1], local_txn[0]);
5451                 assert_eq!(node_txn[0].input.len(), 1);
5452                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5453                 check_spends!(node_txn[0], local_txn[0]);
5454                 node_txn[0].clone()
5455         };
5456
5457         mine_transaction(&nodes[1], &node_tx);
5458         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
5459
5460         // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5461         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5462         assert_eq!(spend_txn.len(), 1);
5463         assert_eq!(spend_txn[0].input.len(), 1);
5464         check_spends!(spend_txn[0], node_tx);
5465         assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5466 }
5467
5468 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5469         // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5470         // unrevoked commitment transaction.
5471         // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5472         // a remote RAA before they could be failed backwards (and combinations thereof).
5473         // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5474         // use the same payment hashes.
5475         // Thus, we use a six-node network:
5476         //
5477         // A \         / E
5478         //    - C - D -
5479         // B /         \ F
5480         // And test where C fails back to A/B when D announces its latest commitment transaction
5481         let chanmon_cfgs = create_chanmon_cfgs(6);
5482         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5483         // When this test was written, the default base fee floated based on the HTLC count.
5484         // It is now fixed, so we simply set the fee to the expected value here.
5485         let mut config = test_default_channel_config();
5486         config.channel_config.forwarding_fee_base_msat = 196;
5487         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
5488                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5489         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5490
5491         let _chan_0_2 = create_announced_chan_between_nodes(&nodes, 0, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5492         let _chan_1_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5493         let chan_2_3 = create_announced_chan_between_nodes(&nodes, 2, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5494         let chan_3_4 = create_announced_chan_between_nodes(&nodes, 3, 4, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5495         let chan_3_5  = create_announced_chan_between_nodes(&nodes, 3, 5, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5496
5497         // Rebalance and check output sanity...
5498         send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
5499         send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
5500         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 2);
5501
5502         let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan_2_3.2).unwrap().holder_dust_limit_satoshis;
5503         // 0th HTLC:
5504         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
5505         // 1st HTLC:
5506         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
5507         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5508         // 2nd HTLC:
5509         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
5510         // 3rd HTLC:
5511         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
5512         // 4th HTLC:
5513         let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5514         // 5th HTLC:
5515         let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5516         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5517         // 6th HTLC:
5518         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());
5519         // 7th HTLC:
5520         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());
5521
5522         // 8th HTLC:
5523         let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5524         // 9th HTLC:
5525         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5526         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
5527
5528         // 10th HTLC:
5529         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
5530         // 11th HTLC:
5531         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5532         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());
5533
5534         // Double-check that six of the new HTLC were added
5535         // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5536         // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5537         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2).len(), 1);
5538         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 8);
5539
5540         // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5541         // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5542         nodes[4].node.fail_htlc_backwards(&payment_hash_1);
5543         nodes[4].node.fail_htlc_backwards(&payment_hash_3);
5544         nodes[4].node.fail_htlc_backwards(&payment_hash_5);
5545         nodes[4].node.fail_htlc_backwards(&payment_hash_6);
5546         check_added_monitors!(nodes[4], 0);
5547
5548         let failed_destinations = vec![
5549                 HTLCDestination::FailedPayment { payment_hash: payment_hash_1 },
5550                 HTLCDestination::FailedPayment { payment_hash: payment_hash_3 },
5551                 HTLCDestination::FailedPayment { payment_hash: payment_hash_5 },
5552                 HTLCDestination::FailedPayment { payment_hash: payment_hash_6 },
5553         ];
5554         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[4], failed_destinations);
5555         check_added_monitors!(nodes[4], 1);
5556
5557         let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5558         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5559         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5560         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5561         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5562         commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5563
5564         // Fail 3rd below-dust and 7th above-dust HTLCs
5565         nodes[5].node.fail_htlc_backwards(&payment_hash_2);
5566         nodes[5].node.fail_htlc_backwards(&payment_hash_4);
5567         check_added_monitors!(nodes[5], 0);
5568
5569         let failed_destinations_2 = vec![
5570                 HTLCDestination::FailedPayment { payment_hash: payment_hash_2 },
5571                 HTLCDestination::FailedPayment { payment_hash: payment_hash_4 },
5572         ];
5573         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[5], failed_destinations_2);
5574         check_added_monitors!(nodes[5], 1);
5575
5576         let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5577         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5578         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5579         commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5580
5581         let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5582
5583         // After 4 and 2 removes respectively above in nodes[4] and nodes[5], nodes[3] should receive 6 PaymentForwardedFailed events
5584         let failed_destinations_3 = vec![
5585                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5586                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5587                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5588                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5589                 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5590                 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5591         ];
5592         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations_3);
5593         check_added_monitors!(nodes[3], 1);
5594         let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5595         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5596         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5597         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5598         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5599         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5600         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5601         if deliver_last_raa {
5602                 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5603         } else {
5604                 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5605         }
5606
5607         // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5608         // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5609         // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5610         // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5611         //
5612         // We now broadcast the latest commitment transaction, which *should* result in failures for
5613         // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5614         // the non-broadcast above-dust HTLCs.
5615         //
5616         // Alternatively, we may broadcast the previous commitment transaction, which should only
5617         // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5618         let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5619
5620         if announce_latest {
5621                 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5622         } else {
5623                 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5624         }
5625         let events = nodes[2].node.get_and_clear_pending_events();
5626         let close_event = if deliver_last_raa {
5627                 assert_eq!(events.len(), 2 + 6);
5628                 events.last().clone().unwrap()
5629         } else {
5630                 assert_eq!(events.len(), 1);
5631                 events.last().clone().unwrap()
5632         };
5633         match close_event {
5634                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5635                 _ => panic!("Unexpected event"),
5636         }
5637
5638         connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5639         check_closed_broadcast!(nodes[2], true);
5640         if deliver_last_raa {
5641                 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5642
5643                 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();
5644                 expect_htlc_handling_failed_destinations!(nodes[2].node.get_and_clear_pending_events(), expected_destinations);
5645         } else {
5646                 let expected_destinations: Vec<HTLCDestination> = if announce_latest {
5647                         repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(9).collect()
5648                 } else {
5649                         repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(6).collect()
5650                 };
5651
5652                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], expected_destinations);
5653         }
5654         check_added_monitors!(nodes[2], 3);
5655
5656         let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5657         assert_eq!(cs_msgs.len(), 2);
5658         let mut a_done = false;
5659         for msg in cs_msgs {
5660                 match msg {
5661                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5662                                 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5663                                 // should be failed-backwards here.
5664                                 let target = if *node_id == nodes[0].node.get_our_node_id() {
5665                                         // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5666                                         for htlc in &updates.update_fail_htlcs {
5667                                                 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 });
5668                                         }
5669                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5670                                         assert!(!a_done);
5671                                         a_done = true;
5672                                         &nodes[0]
5673                                 } else {
5674                                         // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5675                                         for htlc in &updates.update_fail_htlcs {
5676                                                 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5677                                         }
5678                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5679                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5680                                         &nodes[1]
5681                                 };
5682                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5683                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5684                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5685                                 if announce_latest {
5686                                         target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5687                                         if *node_id == nodes[0].node.get_our_node_id() {
5688                                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5689                                         }
5690                                 }
5691                                 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5692                         },
5693                         _ => panic!("Unexpected event"),
5694                 }
5695         }
5696
5697         let as_events = nodes[0].node.get_and_clear_pending_events();
5698         assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5699         let mut as_failds = HashSet::new();
5700         let mut as_updates = 0;
5701         for event in as_events.iter() {
5702                 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref network_update, .. } = event {
5703                         assert!(as_failds.insert(*payment_hash));
5704                         if *payment_hash != payment_hash_2 {
5705                                 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5706                         } else {
5707                                 assert!(!payment_failed_permanently);
5708                         }
5709                         if network_update.is_some() {
5710                                 as_updates += 1;
5711                         }
5712                 } else { panic!("Unexpected event"); }
5713         }
5714         assert!(as_failds.contains(&payment_hash_1));
5715         assert!(as_failds.contains(&payment_hash_2));
5716         if announce_latest {
5717                 assert!(as_failds.contains(&payment_hash_3));
5718                 assert!(as_failds.contains(&payment_hash_5));
5719         }
5720         assert!(as_failds.contains(&payment_hash_6));
5721
5722         let bs_events = nodes[1].node.get_and_clear_pending_events();
5723         assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5724         let mut bs_failds = HashSet::new();
5725         let mut bs_updates = 0;
5726         for event in bs_events.iter() {
5727                 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref network_update, .. } = event {
5728                         assert!(bs_failds.insert(*payment_hash));
5729                         if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5730                                 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5731                         } else {
5732                                 assert!(!payment_failed_permanently);
5733                         }
5734                         if network_update.is_some() {
5735                                 bs_updates += 1;
5736                         }
5737                 } else { panic!("Unexpected event"); }
5738         }
5739         assert!(bs_failds.contains(&payment_hash_1));
5740         assert!(bs_failds.contains(&payment_hash_2));
5741         if announce_latest {
5742                 assert!(bs_failds.contains(&payment_hash_4));
5743         }
5744         assert!(bs_failds.contains(&payment_hash_5));
5745
5746         // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5747         // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5748         // unknown-preimage-etc, B should have gotten 2. Thus, in the
5749         // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5750         assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5751         assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5752 }
5753
5754 #[test]
5755 fn test_fail_backwards_latest_remote_announce_a() {
5756         do_test_fail_backwards_unrevoked_remote_announce(false, true);
5757 }
5758
5759 #[test]
5760 fn test_fail_backwards_latest_remote_announce_b() {
5761         do_test_fail_backwards_unrevoked_remote_announce(true, true);
5762 }
5763
5764 #[test]
5765 fn test_fail_backwards_previous_remote_announce() {
5766         do_test_fail_backwards_unrevoked_remote_announce(false, false);
5767         // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5768         // tested for in test_commitment_revoked_fail_backward_exhaustive()
5769 }
5770
5771 #[test]
5772 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5773         let chanmon_cfgs = create_chanmon_cfgs(2);
5774         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5775         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5776         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5777
5778         // Create some initial channels
5779         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5780
5781         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5782         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5783         assert_eq!(local_txn[0].input.len(), 1);
5784         check_spends!(local_txn[0], chan_1.3);
5785
5786         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5787         mine_transaction(&nodes[0], &local_txn[0]);
5788         check_closed_broadcast!(nodes[0], true);
5789         check_added_monitors!(nodes[0], 1);
5790         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5791         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5792
5793         let htlc_timeout = {
5794                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5795                 assert_eq!(node_txn.len(), 2);
5796                 check_spends!(node_txn[0], chan_1.3);
5797                 assert_eq!(node_txn[1].input.len(), 1);
5798                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5799                 check_spends!(node_txn[1], local_txn[0]);
5800                 node_txn[1].clone()
5801         };
5802
5803         mine_transaction(&nodes[0], &htlc_timeout);
5804         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5805         expect_payment_failed!(nodes[0], our_payment_hash, false);
5806
5807         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5808         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5809         assert_eq!(spend_txn.len(), 3);
5810         check_spends!(spend_txn[0], local_txn[0]);
5811         assert_eq!(spend_txn[1].input.len(), 1);
5812         check_spends!(spend_txn[1], htlc_timeout);
5813         assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5814         assert_eq!(spend_txn[2].input.len(), 2);
5815         check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5816         assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5817                 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5818 }
5819
5820 #[test]
5821 fn test_key_derivation_params() {
5822         // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5823         // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5824         // let us re-derive the channel key set to then derive a delayed_payment_key.
5825
5826         let chanmon_cfgs = create_chanmon_cfgs(3);
5827
5828         // We manually create the node configuration to backup the seed.
5829         let seed = [42; 32];
5830         let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5831         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);
5832         let network_graph = NetworkGraph::new(chanmon_cfgs[0].chain_source.genesis_hash, &chanmon_cfgs[0].logger);
5833         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() };
5834         let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5835         node_cfgs.remove(0);
5836         node_cfgs.insert(0, node);
5837
5838         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5839         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5840
5841         // Create some initial channels
5842         // Create a dummy channel to advance index by one and thus test re-derivation correctness
5843         // for node 0
5844         let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5845         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5846         assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5847
5848         // Ensure all nodes are at the same height
5849         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5850         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5851         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5852         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5853
5854         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5855         let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5856         let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5857         assert_eq!(local_txn_1[0].input.len(), 1);
5858         check_spends!(local_txn_1[0], chan_1.3);
5859
5860         // We check funding pubkey are unique
5861         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]));
5862         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]));
5863         if from_0_funding_key_0 == from_1_funding_key_0
5864             || from_0_funding_key_0 == from_1_funding_key_1
5865             || from_0_funding_key_1 == from_1_funding_key_0
5866             || from_0_funding_key_1 == from_1_funding_key_1 {
5867                 panic!("Funding pubkeys aren't unique");
5868         }
5869
5870         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5871         mine_transaction(&nodes[0], &local_txn_1[0]);
5872         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5873         check_closed_broadcast!(nodes[0], true);
5874         check_added_monitors!(nodes[0], 1);
5875         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5876
5877         let htlc_timeout = {
5878                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5879                 assert_eq!(node_txn[1].input.len(), 1);
5880                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5881                 check_spends!(node_txn[1], local_txn_1[0]);
5882                 node_txn[1].clone()
5883         };
5884
5885         mine_transaction(&nodes[0], &htlc_timeout);
5886         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5887         expect_payment_failed!(nodes[0], our_payment_hash, false);
5888
5889         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5890         let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5891         let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5892         assert_eq!(spend_txn.len(), 3);
5893         check_spends!(spend_txn[0], local_txn_1[0]);
5894         assert_eq!(spend_txn[1].input.len(), 1);
5895         check_spends!(spend_txn[1], htlc_timeout);
5896         assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5897         assert_eq!(spend_txn[2].input.len(), 2);
5898         check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5899         assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5900                 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5901 }
5902
5903 #[test]
5904 fn test_static_output_closing_tx() {
5905         let chanmon_cfgs = create_chanmon_cfgs(2);
5906         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5907         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5908         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5909
5910         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5911
5912         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5913         let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5914
5915         mine_transaction(&nodes[0], &closing_tx);
5916         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5917         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5918
5919         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5920         assert_eq!(spend_txn.len(), 1);
5921         check_spends!(spend_txn[0], closing_tx);
5922
5923         mine_transaction(&nodes[1], &closing_tx);
5924         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5925         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5926
5927         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5928         assert_eq!(spend_txn.len(), 1);
5929         check_spends!(spend_txn[0], closing_tx);
5930 }
5931
5932 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5933         let chanmon_cfgs = create_chanmon_cfgs(2);
5934         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5935         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5936         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5937         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5938
5939         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3_000_000 });
5940
5941         // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5942         // present in B's local commitment transaction, but none of A's commitment transactions.
5943         nodes[1].node.claim_funds(payment_preimage);
5944         check_added_monitors!(nodes[1], 1);
5945         expect_payment_claimed!(nodes[1], payment_hash, if use_dust { 50000 } else { 3_000_000 });
5946
5947         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5948         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5949         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
5950
5951         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5952         check_added_monitors!(nodes[0], 1);
5953         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5954         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5955         check_added_monitors!(nodes[1], 1);
5956
5957         let starting_block = nodes[1].best_block_info();
5958         let mut block = Block {
5959                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
5960                 txdata: vec![],
5961         };
5962         for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5963                 connect_block(&nodes[1], &block);
5964                 block.header.prev_blockhash = block.block_hash();
5965         }
5966         test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5967         check_closed_broadcast!(nodes[1], true);
5968         check_added_monitors!(nodes[1], 1);
5969         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5970 }
5971
5972 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5973         let chanmon_cfgs = create_chanmon_cfgs(2);
5974         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5975         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5976         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5977         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5978
5979         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5980         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
5981         check_added_monitors!(nodes[0], 1);
5982
5983         let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5984
5985         // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5986         // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5987         // to "time out" the HTLC.
5988
5989         let starting_block = nodes[1].best_block_info();
5990         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
5991
5992         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5993                 connect_block(&nodes[0], &Block { header, txdata: Vec::new()});
5994                 header.prev_blockhash = header.block_hash();
5995         }
5996         test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5997         check_closed_broadcast!(nodes[0], true);
5998         check_added_monitors!(nodes[0], 1);
5999         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6000 }
6001
6002 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
6003         let chanmon_cfgs = create_chanmon_cfgs(3);
6004         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6005         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6006         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6007         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6008
6009         // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
6010         // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
6011         // Also optionally test that we *don't* fail the channel in case the commitment transaction was
6012         // actually revoked.
6013         let htlc_value = if use_dust { 50000 } else { 3000000 };
6014         let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
6015         nodes[1].node.fail_htlc_backwards(&our_payment_hash);
6016         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
6017         check_added_monitors!(nodes[1], 1);
6018
6019         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6020         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
6021         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
6022         check_added_monitors!(nodes[0], 1);
6023         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6024         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
6025         check_added_monitors!(nodes[1], 1);
6026         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
6027         check_added_monitors!(nodes[1], 1);
6028         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
6029
6030         if check_revoke_no_close {
6031                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
6032                 check_added_monitors!(nodes[0], 1);
6033         }
6034
6035         let starting_block = nodes[1].best_block_info();
6036         let mut block = Block {
6037                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
6038                 txdata: vec![],
6039         };
6040         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
6041                 connect_block(&nodes[0], &block);
6042                 block.header.prev_blockhash = block.block_hash();
6043         }
6044         if !check_revoke_no_close {
6045                 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
6046                 check_closed_broadcast!(nodes[0], true);
6047                 check_added_monitors!(nodes[0], 1);
6048                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6049         } else {
6050                 let events = nodes[0].node.get_and_clear_pending_events();
6051                 assert_eq!(events.len(), 2);
6052                 if let Event::PaymentPathFailed { ref payment_hash, .. } = events[0] {
6053                         assert_eq!(*payment_hash, our_payment_hash);
6054                 } else { panic!("Unexpected event"); }
6055                 if let Event::PaymentFailed { ref payment_hash, .. } = events[1] {
6056                         assert_eq!(*payment_hash, our_payment_hash);
6057                 } else { panic!("Unexpected event"); }
6058         }
6059 }
6060
6061 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
6062 // There are only a few cases to test here:
6063 //  * its not really normative behavior, but we test that below-dust HTLCs "included" in
6064 //    broadcastable commitment transactions result in channel closure,
6065 //  * its included in an unrevoked-but-previous remote commitment transaction,
6066 //  * its included in the latest remote or local commitment transactions.
6067 // We test each of the three possible commitment transactions individually and use both dust and
6068 // non-dust HTLCs.
6069 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
6070 // assume they are handled the same across all six cases, as both outbound and inbound failures are
6071 // tested for at least one of the cases in other tests.
6072 #[test]
6073 fn htlc_claim_single_commitment_only_a() {
6074         do_htlc_claim_local_commitment_only(true);
6075         do_htlc_claim_local_commitment_only(false);
6076
6077         do_htlc_claim_current_remote_commitment_only(true);
6078         do_htlc_claim_current_remote_commitment_only(false);
6079 }
6080
6081 #[test]
6082 fn htlc_claim_single_commitment_only_b() {
6083         do_htlc_claim_previous_remote_commitment_only(true, false);
6084         do_htlc_claim_previous_remote_commitment_only(false, false);
6085         do_htlc_claim_previous_remote_commitment_only(true, true);
6086         do_htlc_claim_previous_remote_commitment_only(false, true);
6087 }
6088
6089 #[test]
6090 #[should_panic]
6091 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
6092         let chanmon_cfgs = create_chanmon_cfgs(2);
6093         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6094         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6095         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6096         // Force duplicate randomness for every get-random call
6097         for node in nodes.iter() {
6098                 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
6099         }
6100
6101         // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
6102         let channel_value_satoshis=10000;
6103         let push_msat=10001;
6104         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
6105         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6106         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &node0_to_1_send_open_channel);
6107         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
6108
6109         // Create a second channel with the same random values. This used to panic due to a colliding
6110         // channel_id, but now panics due to a colliding outbound SCID alias.
6111         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6112 }
6113
6114 #[test]
6115 fn bolt2_open_channel_sending_node_checks_part2() {
6116         let chanmon_cfgs = create_chanmon_cfgs(2);
6117         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6118         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6119         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6120
6121         // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
6122         let channel_value_satoshis=2^24;
6123         let push_msat=10001;
6124         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6125
6126         // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
6127         let channel_value_satoshis=10000;
6128         // Test when push_msat is equal to 1000 * funding_satoshis.
6129         let push_msat=1000*channel_value_satoshis+1;
6130         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6131
6132         // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
6133         let channel_value_satoshis=10000;
6134         let push_msat=10001;
6135         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
6136         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6137         assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
6138
6139         // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
6140         // 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
6141         assert!(node0_to_1_send_open_channel.channel_flags<=1);
6142
6143         // 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.
6144         assert!(BREAKDOWN_TIMEOUT>0);
6145         assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
6146
6147         // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
6148         let chain_hash=genesis_block(Network::Testnet).header.block_hash();
6149         assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
6150
6151         // 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.
6152         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
6153         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
6154         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
6155         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
6156         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
6157 }
6158
6159 #[test]
6160 fn bolt2_open_channel_sane_dust_limit() {
6161         let chanmon_cfgs = create_chanmon_cfgs(2);
6162         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6163         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6164         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6165
6166         let channel_value_satoshis=1000000;
6167         let push_msat=10001;
6168         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
6169         let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6170         node0_to_1_send_open_channel.dust_limit_satoshis = 547;
6171         node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
6172
6173         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &node0_to_1_send_open_channel);
6174         let events = nodes[1].node.get_and_clear_pending_msg_events();
6175         let err_msg = match events[0] {
6176                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
6177                         msg.clone()
6178                 },
6179                 _ => panic!("Unexpected event"),
6180         };
6181         assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
6182 }
6183
6184 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
6185 // originated from our node, its failure is surfaced to the user. We trigger this failure to
6186 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
6187 // is no longer affordable once it's freed.
6188 #[test]
6189 fn test_fail_holding_cell_htlc_upon_free() {
6190         let chanmon_cfgs = create_chanmon_cfgs(2);
6191         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6192         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6193         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6194         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6195
6196         // First nodes[0] generates an update_fee, setting the channel's
6197         // pending_update_fee.
6198         {
6199                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6200                 *feerate_lock += 20;
6201         }
6202         nodes[0].node.timer_tick_occurred();
6203         check_added_monitors!(nodes[0], 1);
6204
6205         let events = nodes[0].node.get_and_clear_pending_msg_events();
6206         assert_eq!(events.len(), 1);
6207         let (update_msg, commitment_signed) = match events[0] {
6208                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6209                         (update_fee.as_ref(), commitment_signed)
6210                 },
6211                 _ => panic!("Unexpected event"),
6212         };
6213
6214         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6215
6216         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6217         let channel_reserve = chan_stat.channel_reserve_msat;
6218         let feerate = get_feerate!(nodes[0], chan.2);
6219         let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6220
6221         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6222         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6223         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6224
6225         // Send a payment which passes reserve checks but gets stuck in the holding cell.
6226         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6227         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6228         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6229
6230         // Flush the pending fee update.
6231         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6232         let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6233         check_added_monitors!(nodes[1], 1);
6234         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
6235         check_added_monitors!(nodes[0], 1);
6236
6237         // Upon receipt of the RAA, there will be an attempt to resend the holding cell
6238         // HTLC, but now that the fee has been raised the payment will now fail, causing
6239         // us to surface its failure to the user.
6240         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6241         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6242         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);
6243         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 {}",
6244                 hex::encode(our_payment_hash.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6245         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6246
6247         // Check that the payment failed to be sent out.
6248         let events = nodes[0].node.get_and_clear_pending_events();
6249         assert_eq!(events.len(), 1);
6250         match &events[0] {
6251                 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, ref network_update, ref all_paths_failed, ref short_channel_id, .. } => {
6252                         assert_eq!(PaymentId(our_payment_hash.0), *payment_id.as_ref().unwrap());
6253                         assert_eq!(our_payment_hash.clone(), *payment_hash);
6254                         assert_eq!(*payment_failed_permanently, false);
6255                         assert_eq!(*all_paths_failed, true);
6256                         assert_eq!(*network_update, None);
6257                         assert_eq!(*short_channel_id, Some(route.paths[0][0].short_channel_id));
6258                 },
6259                 _ => panic!("Unexpected event"),
6260         }
6261 }
6262
6263 // Test that if multiple HTLCs are released from the holding cell and one is
6264 // valid but the other is no longer valid upon release, the valid HTLC can be
6265 // successfully completed while the other one fails as expected.
6266 #[test]
6267 fn test_free_and_fail_holding_cell_htlcs() {
6268         let chanmon_cfgs = create_chanmon_cfgs(2);
6269         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6270         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6271         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6272         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6273
6274         // First nodes[0] generates an update_fee, setting the channel's
6275         // pending_update_fee.
6276         {
6277                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6278                 *feerate_lock += 200;
6279         }
6280         nodes[0].node.timer_tick_occurred();
6281         check_added_monitors!(nodes[0], 1);
6282
6283         let events = nodes[0].node.get_and_clear_pending_msg_events();
6284         assert_eq!(events.len(), 1);
6285         let (update_msg, commitment_signed) = match events[0] {
6286                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6287                         (update_fee.as_ref(), commitment_signed)
6288                 },
6289                 _ => panic!("Unexpected event"),
6290         };
6291
6292         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6293
6294         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6295         let channel_reserve = chan_stat.channel_reserve_msat;
6296         let feerate = get_feerate!(nodes[0], chan.2);
6297         let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6298
6299         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6300         let amt_1 = 20000;
6301         let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors) - amt_1;
6302         let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
6303         let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
6304
6305         // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6306         nodes[0].node.send_payment(&route_1, payment_hash_1, &Some(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
6307         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6308         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6309         let payment_id_2 = PaymentId(nodes[0].keys_manager.get_secure_random_bytes());
6310         nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2), payment_id_2).unwrap();
6311         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6312         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6313
6314         // Flush the pending fee update.
6315         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6316         let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6317         check_added_monitors!(nodes[1], 1);
6318         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6319         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6320         check_added_monitors!(nodes[0], 2);
6321
6322         // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6323         // but now that the fee has been raised the second payment will now fail, causing us
6324         // to surface its failure to the user. The first payment should succeed.
6325         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6326         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6327         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);
6328         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 {}",
6329                 hex::encode(payment_hash_2.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6330         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6331
6332         // Check that the second payment failed to be sent out.
6333         let events = nodes[0].node.get_and_clear_pending_events();
6334         assert_eq!(events.len(), 1);
6335         match &events[0] {
6336                 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, ref network_update, ref all_paths_failed, ref short_channel_id, .. } => {
6337                         assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
6338                         assert_eq!(payment_hash_2.clone(), *payment_hash);
6339                         assert_eq!(*payment_failed_permanently, false);
6340                         assert_eq!(*all_paths_failed, true);
6341                         assert_eq!(*network_update, None);
6342                         assert_eq!(*short_channel_id, Some(route_2.paths[0][0].short_channel_id));
6343                 },
6344                 _ => panic!("Unexpected event"),
6345         }
6346
6347         // Complete the first payment and the RAA from the fee update.
6348         let (payment_event, send_raa_event) = {
6349                 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6350                 assert_eq!(msgs.len(), 2);
6351                 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6352         };
6353         let raa = match send_raa_event {
6354                 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6355                 _ => panic!("Unexpected event"),
6356         };
6357         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6358         check_added_monitors!(nodes[1], 1);
6359         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6360         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6361         let events = nodes[1].node.get_and_clear_pending_events();
6362         assert_eq!(events.len(), 1);
6363         match events[0] {
6364                 Event::PendingHTLCsForwardable { .. } => {},
6365                 _ => panic!("Unexpected event"),
6366         }
6367         nodes[1].node.process_pending_htlc_forwards();
6368         let events = nodes[1].node.get_and_clear_pending_events();
6369         assert_eq!(events.len(), 1);
6370         match events[0] {
6371                 Event::PaymentReceived { .. } => {},
6372                 _ => panic!("Unexpected event"),
6373         }
6374         nodes[1].node.claim_funds(payment_preimage_1);
6375         check_added_monitors!(nodes[1], 1);
6376         expect_payment_claimed!(nodes[1], payment_hash_1, amt_1);
6377
6378         let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6379         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6380         commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6381         expect_payment_sent!(nodes[0], payment_preimage_1);
6382 }
6383
6384 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6385 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6386 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6387 // once it's freed.
6388 #[test]
6389 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6390         let chanmon_cfgs = create_chanmon_cfgs(3);
6391         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6392         // When this test was written, the default base fee floated based on the HTLC count.
6393         // It is now fixed, so we simply set the fee to the expected value here.
6394         let mut config = test_default_channel_config();
6395         config.channel_config.forwarding_fee_base_msat = 196;
6396         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
6397         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6398         let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6399         let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6400
6401         // First nodes[1] generates an update_fee, setting the channel's
6402         // pending_update_fee.
6403         {
6404                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
6405                 *feerate_lock += 20;
6406         }
6407         nodes[1].node.timer_tick_occurred();
6408         check_added_monitors!(nodes[1], 1);
6409
6410         let events = nodes[1].node.get_and_clear_pending_msg_events();
6411         assert_eq!(events.len(), 1);
6412         let (update_msg, commitment_signed) = match events[0] {
6413                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6414                         (update_fee.as_ref(), commitment_signed)
6415                 },
6416                 _ => panic!("Unexpected event"),
6417         };
6418
6419         nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6420
6421         let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
6422         let channel_reserve = chan_stat.channel_reserve_msat;
6423         let feerate = get_feerate!(nodes[0], chan_0_1.2);
6424         let opt_anchors = get_opt_anchors!(nodes[0], chan_0_1.2);
6425
6426         // Send a payment which passes reserve checks but gets stuck in the holding cell.
6427         let feemsat = 239;
6428         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
6429         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors) - total_routing_fee_msat;
6430         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
6431         let payment_event = {
6432                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6433                 check_added_monitors!(nodes[0], 1);
6434
6435                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6436                 assert_eq!(events.len(), 1);
6437
6438                 SendEvent::from_event(events.remove(0))
6439         };
6440         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6441         check_added_monitors!(nodes[1], 0);
6442         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6443         expect_pending_htlcs_forwardable!(nodes[1]);
6444
6445         chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
6446         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6447
6448         // Flush the pending fee update.
6449         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6450         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6451         check_added_monitors!(nodes[2], 1);
6452         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6453         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6454         check_added_monitors!(nodes[1], 2);
6455
6456         // A final RAA message is generated to finalize the fee update.
6457         let events = nodes[1].node.get_and_clear_pending_msg_events();
6458         assert_eq!(events.len(), 1);
6459
6460         let raa_msg = match &events[0] {
6461                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6462                         msg.clone()
6463                 },
6464                 _ => panic!("Unexpected event"),
6465         };
6466
6467         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6468         check_added_monitors!(nodes[2], 1);
6469         assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6470
6471         // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6472         let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6473         assert_eq!(process_htlc_forwards_event.len(), 2);
6474         match &process_htlc_forwards_event[0] {
6475                 &Event::PendingHTLCsForwardable { .. } => {},
6476                 _ => panic!("Unexpected event"),
6477         }
6478
6479         // In response, we call ChannelManager's process_pending_htlc_forwards
6480         nodes[1].node.process_pending_htlc_forwards();
6481         check_added_monitors!(nodes[1], 1);
6482
6483         // This causes the HTLC to be failed backwards.
6484         let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6485         assert_eq!(fail_event.len(), 1);
6486         let (fail_msg, commitment_signed) = match &fail_event[0] {
6487                 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6488                         assert_eq!(updates.update_add_htlcs.len(), 0);
6489                         assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6490                         assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6491                         assert_eq!(updates.update_fail_htlcs.len(), 1);
6492                         (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6493                 },
6494                 _ => panic!("Unexpected event"),
6495         };
6496
6497         // Pass the failure messages back to nodes[0].
6498         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6499         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6500
6501         // Complete the HTLC failure+removal process.
6502         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6503         check_added_monitors!(nodes[0], 1);
6504         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6505         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6506         check_added_monitors!(nodes[1], 2);
6507         let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6508         assert_eq!(final_raa_event.len(), 1);
6509         let raa = match &final_raa_event[0] {
6510                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6511                 _ => panic!("Unexpected event"),
6512         };
6513         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6514         expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6515         check_added_monitors!(nodes[0], 1);
6516 }
6517
6518 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6519 // 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.
6520 //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.
6521
6522 #[test]
6523 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6524         //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6525         let chanmon_cfgs = create_chanmon_cfgs(2);
6526         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6527         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6528         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6529         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6530
6531         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6532         route.paths[0][0].fee_msat = 100;
6533
6534         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 },
6535                 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6536         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6537         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6538 }
6539
6540 #[test]
6541 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6542         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6543         let chanmon_cfgs = create_chanmon_cfgs(2);
6544         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6545         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6546         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6547         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6548
6549         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6550         route.paths[0][0].fee_msat = 0;
6551         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 },
6552                 assert_eq!(err, "Cannot send 0-msat HTLC"));
6553
6554         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6555         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6556 }
6557
6558 #[test]
6559 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6560         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6561         let chanmon_cfgs = create_chanmon_cfgs(2);
6562         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6563         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6564         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6565         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6566
6567         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6568         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6569         check_added_monitors!(nodes[0], 1);
6570         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6571         updates.update_add_htlcs[0].amount_msat = 0;
6572
6573         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6574         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6575         check_closed_broadcast!(nodes[1], true).unwrap();
6576         check_added_monitors!(nodes[1], 1);
6577         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
6578 }
6579
6580 #[test]
6581 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6582         //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6583         //It is enforced when constructing a route.
6584         let chanmon_cfgs = create_chanmon_cfgs(2);
6585         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6586         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6587         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6588         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6589
6590         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
6591                 .with_features(channelmanager::provided_invoice_features());
6592         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000, 0);
6593         route.paths[0].last_mut().unwrap().cltv_expiry_delta = 500000001;
6594         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 },
6595                 assert_eq!(err, &"Channel CLTV overflowed?"));
6596 }
6597
6598 #[test]
6599 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6600         //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.
6601         //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6602         //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6603         let chanmon_cfgs = create_chanmon_cfgs(2);
6604         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6605         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6606         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6607         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6608         let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6609
6610         for i in 0..max_accepted_htlcs {
6611                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6612                 let payment_event = {
6613                         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6614                         check_added_monitors!(nodes[0], 1);
6615
6616                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6617                         assert_eq!(events.len(), 1);
6618                         if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6619                                 assert_eq!(htlcs[0].htlc_id, i);
6620                         } else {
6621                                 assert!(false);
6622                         }
6623                         SendEvent::from_event(events.remove(0))
6624                 };
6625                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6626                 check_added_monitors!(nodes[1], 0);
6627                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6628
6629                 expect_pending_htlcs_forwardable!(nodes[1]);
6630                 expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6631         }
6632         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6633         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 },
6634                 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6635
6636         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6637         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6638 }
6639
6640 #[test]
6641 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6642         //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.
6643         let chanmon_cfgs = create_chanmon_cfgs(2);
6644         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6645         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6646         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6647         let channel_value = 100000;
6648         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6649         let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6650
6651         send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6652
6653         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6654         // Manually create a route over our max in flight (which our router normally automatically
6655         // limits us to.
6656         route.paths[0][0].fee_msat =  max_in_flight + 1;
6657         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 },
6658                 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)));
6659
6660         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6661         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);
6662
6663         send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6664 }
6665
6666 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6667 #[test]
6668 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6669         //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6670         let chanmon_cfgs = create_chanmon_cfgs(2);
6671         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6672         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6673         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6674         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6675         let htlc_minimum_msat: u64;
6676         {
6677                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6678                 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6679                 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6680         }
6681
6682         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6683         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6684         check_added_monitors!(nodes[0], 1);
6685         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6686         updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6687         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6688         assert!(nodes[1].node.list_channels().is_empty());
6689         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6690         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()));
6691         check_added_monitors!(nodes[1], 1);
6692         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6693 }
6694
6695 #[test]
6696 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6697         //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
6698         let chanmon_cfgs = create_chanmon_cfgs(2);
6699         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6700         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6701         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6702         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6703
6704         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6705         let channel_reserve = chan_stat.channel_reserve_msat;
6706         let feerate = get_feerate!(nodes[0], chan.2);
6707         let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6708         // The 2* and +1 are for the fee spike reserve.
6709         let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6710
6711         let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6712         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6713         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6714         check_added_monitors!(nodes[0], 1);
6715         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6716
6717         // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6718         // at this time channel-initiatee receivers are not required to enforce that senders
6719         // respect the fee_spike_reserve.
6720         updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6721         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6722
6723         assert!(nodes[1].node.list_channels().is_empty());
6724         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6725         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6726         check_added_monitors!(nodes[1], 1);
6727         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6728 }
6729
6730 #[test]
6731 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6732         //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6733         //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6734         let chanmon_cfgs = create_chanmon_cfgs(2);
6735         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6736         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6737         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6738         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6739
6740         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3999999);
6741         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6742         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6743         let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6744         let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &Some(our_payment_secret), cur_height, &None).unwrap();
6745         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6746
6747         let mut msg = msgs::UpdateAddHTLC {
6748                 channel_id: chan.2,
6749                 htlc_id: 0,
6750                 amount_msat: 1000,
6751                 payment_hash: our_payment_hash,
6752                 cltv_expiry: htlc_cltv,
6753                 onion_routing_packet: onion_packet.clone(),
6754         };
6755
6756         for i in 0..super::channel::OUR_MAX_HTLCS {
6757                 msg.htlc_id = i as u64;
6758                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6759         }
6760         msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6761         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6762
6763         assert!(nodes[1].node.list_channels().is_empty());
6764         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6765         assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6766         check_added_monitors!(nodes[1], 1);
6767         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6768 }
6769
6770 #[test]
6771 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6772         //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6773         let chanmon_cfgs = create_chanmon_cfgs(2);
6774         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6775         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6776         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6777         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6778
6779         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6780         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6781         check_added_monitors!(nodes[0], 1);
6782         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6783         updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6784         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6785
6786         assert!(nodes[1].node.list_channels().is_empty());
6787         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6788         assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6789         check_added_monitors!(nodes[1], 1);
6790         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6791 }
6792
6793 #[test]
6794 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6795         //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6796         let chanmon_cfgs = create_chanmon_cfgs(2);
6797         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6798         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6799         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6800
6801         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6802         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6803         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6804         check_added_monitors!(nodes[0], 1);
6805         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6806         updates.update_add_htlcs[0].cltv_expiry = 500000000;
6807         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6808
6809         assert!(nodes[1].node.list_channels().is_empty());
6810         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6811         assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6812         check_added_monitors!(nodes[1], 1);
6813         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6814 }
6815
6816 #[test]
6817 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6818         //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6819         // We test this by first testing that that repeated HTLCs pass commitment signature checks
6820         // after disconnect and that non-sequential htlc_ids result in a channel failure.
6821         let chanmon_cfgs = create_chanmon_cfgs(2);
6822         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6823         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6824         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6825
6826         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6827         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6828         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6829         check_added_monitors!(nodes[0], 1);
6830         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6831         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6832
6833         //Disconnect and Reconnect
6834         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6835         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6836         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
6837         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6838         assert_eq!(reestablish_1.len(), 1);
6839         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
6840         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6841         assert_eq!(reestablish_2.len(), 1);
6842         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6843         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6844         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6845         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6846
6847         //Resend HTLC
6848         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6849         assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6850         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6851         check_added_monitors!(nodes[1], 1);
6852         let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6853
6854         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6855
6856         assert!(nodes[1].node.list_channels().is_empty());
6857         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6858         assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6859         check_added_monitors!(nodes[1], 1);
6860         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6861 }
6862
6863 #[test]
6864 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6865         //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.
6866
6867         let chanmon_cfgs = create_chanmon_cfgs(2);
6868         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6869         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6870         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6871         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6872         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6873         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6874
6875         check_added_monitors!(nodes[0], 1);
6876         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6877         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6878
6879         let update_msg = msgs::UpdateFulfillHTLC{
6880                 channel_id: chan.2,
6881                 htlc_id: 0,
6882                 payment_preimage: our_payment_preimage,
6883         };
6884
6885         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6886
6887         assert!(nodes[0].node.list_channels().is_empty());
6888         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6889         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()));
6890         check_added_monitors!(nodes[0], 1);
6891         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6892 }
6893
6894 #[test]
6895 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6896         //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.
6897
6898         let chanmon_cfgs = create_chanmon_cfgs(2);
6899         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6900         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6901         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6902         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6903
6904         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6905         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6906         check_added_monitors!(nodes[0], 1);
6907         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6908         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6909
6910         let update_msg = msgs::UpdateFailHTLC{
6911                 channel_id: chan.2,
6912                 htlc_id: 0,
6913                 reason: msgs::OnionErrorPacket { data: Vec::new()},
6914         };
6915
6916         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6917
6918         assert!(nodes[0].node.list_channels().is_empty());
6919         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6920         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()));
6921         check_added_monitors!(nodes[0], 1);
6922         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6923 }
6924
6925 #[test]
6926 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6927         //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.
6928
6929         let chanmon_cfgs = create_chanmon_cfgs(2);
6930         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6931         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6932         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6933         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6934
6935         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6936         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6937         check_added_monitors!(nodes[0], 1);
6938         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6939         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6940         let update_msg = msgs::UpdateFailMalformedHTLC{
6941                 channel_id: chan.2,
6942                 htlc_id: 0,
6943                 sha256_of_onion: [1; 32],
6944                 failure_code: 0x8000,
6945         };
6946
6947         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6948
6949         assert!(nodes[0].node.list_channels().is_empty());
6950         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6951         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()));
6952         check_added_monitors!(nodes[0], 1);
6953         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6954 }
6955
6956 #[test]
6957 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6958         //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6959
6960         let chanmon_cfgs = create_chanmon_cfgs(2);
6961         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6962         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6963         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6964         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6965
6966         let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6967
6968         nodes[1].node.claim_funds(our_payment_preimage);
6969         check_added_monitors!(nodes[1], 1);
6970         expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6971
6972         let events = nodes[1].node.get_and_clear_pending_msg_events();
6973         assert_eq!(events.len(), 1);
6974         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6975                 match events[0] {
6976                         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, .. } } => {
6977                                 assert!(update_add_htlcs.is_empty());
6978                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6979                                 assert!(update_fail_htlcs.is_empty());
6980                                 assert!(update_fail_malformed_htlcs.is_empty());
6981                                 assert!(update_fee.is_none());
6982                                 update_fulfill_htlcs[0].clone()
6983                         },
6984                         _ => panic!("Unexpected event"),
6985                 }
6986         };
6987
6988         update_fulfill_msg.htlc_id = 1;
6989
6990         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6991
6992         assert!(nodes[0].node.list_channels().is_empty());
6993         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6994         assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6995         check_added_monitors!(nodes[0], 1);
6996         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6997 }
6998
6999 #[test]
7000 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
7001         //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.
7002
7003         let chanmon_cfgs = create_chanmon_cfgs(2);
7004         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7005         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7006         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7007         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7008
7009         let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
7010
7011         nodes[1].node.claim_funds(our_payment_preimage);
7012         check_added_monitors!(nodes[1], 1);
7013         expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
7014
7015         let events = nodes[1].node.get_and_clear_pending_msg_events();
7016         assert_eq!(events.len(), 1);
7017         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
7018                 match events[0] {
7019                         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, .. } } => {
7020                                 assert!(update_add_htlcs.is_empty());
7021                                 assert_eq!(update_fulfill_htlcs.len(), 1);
7022                                 assert!(update_fail_htlcs.is_empty());
7023                                 assert!(update_fail_malformed_htlcs.is_empty());
7024                                 assert!(update_fee.is_none());
7025                                 update_fulfill_htlcs[0].clone()
7026                         },
7027                         _ => panic!("Unexpected event"),
7028                 }
7029         };
7030
7031         update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
7032
7033         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
7034
7035         assert!(nodes[0].node.list_channels().is_empty());
7036         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
7037         assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
7038         check_added_monitors!(nodes[0], 1);
7039         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
7040 }
7041
7042 #[test]
7043 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
7044         //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.
7045
7046         let chanmon_cfgs = create_chanmon_cfgs(2);
7047         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7048         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7049         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7050         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7051
7052         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
7053         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
7054         check_added_monitors!(nodes[0], 1);
7055
7056         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7057         updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
7058
7059         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
7060         check_added_monitors!(nodes[1], 0);
7061         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
7062
7063         let events = nodes[1].node.get_and_clear_pending_msg_events();
7064
7065         let mut update_msg: msgs::UpdateFailMalformedHTLC = {
7066                 match events[0] {
7067                         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, .. } } => {
7068                                 assert!(update_add_htlcs.is_empty());
7069                                 assert!(update_fulfill_htlcs.is_empty());
7070                                 assert!(update_fail_htlcs.is_empty());
7071                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
7072                                 assert!(update_fee.is_none());
7073                                 update_fail_malformed_htlcs[0].clone()
7074                         },
7075                         _ => panic!("Unexpected event"),
7076                 }
7077         };
7078         update_msg.failure_code &= !0x8000;
7079         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
7080
7081         assert!(nodes[0].node.list_channels().is_empty());
7082         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
7083         assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
7084         check_added_monitors!(nodes[0], 1);
7085         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
7086 }
7087
7088 #[test]
7089 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
7090         //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
7091         //    * 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.
7092
7093         let chanmon_cfgs = create_chanmon_cfgs(3);
7094         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7095         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7096         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7097         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7098         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7099
7100         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
7101
7102         //First hop
7103         let mut payment_event = {
7104                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
7105                 check_added_monitors!(nodes[0], 1);
7106                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7107                 assert_eq!(events.len(), 1);
7108                 SendEvent::from_event(events.remove(0))
7109         };
7110         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7111         check_added_monitors!(nodes[1], 0);
7112         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7113         expect_pending_htlcs_forwardable!(nodes[1]);
7114         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7115         assert_eq!(events_2.len(), 1);
7116         check_added_monitors!(nodes[1], 1);
7117         payment_event = SendEvent::from_event(events_2.remove(0));
7118         assert_eq!(payment_event.msgs.len(), 1);
7119
7120         //Second Hop
7121         payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
7122         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
7123         check_added_monitors!(nodes[2], 0);
7124         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
7125
7126         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
7127         assert_eq!(events_3.len(), 1);
7128         let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
7129                 match events_3[0] {
7130                         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 } } => {
7131                                 assert!(update_add_htlcs.is_empty());
7132                                 assert!(update_fulfill_htlcs.is_empty());
7133                                 assert!(update_fail_htlcs.is_empty());
7134                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
7135                                 assert!(update_fee.is_none());
7136                                 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
7137                         },
7138                         _ => panic!("Unexpected event"),
7139                 }
7140         };
7141
7142         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
7143
7144         check_added_monitors!(nodes[1], 0);
7145         commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
7146         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 }]);
7147         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
7148         assert_eq!(events_4.len(), 1);
7149
7150         //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
7151         match events_4[0] {
7152                 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, .. } } => {
7153                         assert!(update_add_htlcs.is_empty());
7154                         assert!(update_fulfill_htlcs.is_empty());
7155                         assert_eq!(update_fail_htlcs.len(), 1);
7156                         assert!(update_fail_malformed_htlcs.is_empty());
7157                         assert!(update_fee.is_none());
7158                 },
7159                 _ => panic!("Unexpected event"),
7160         };
7161
7162         check_added_monitors!(nodes[1], 1);
7163 }
7164
7165 #[test]
7166 fn test_channel_failed_after_message_with_badonion_node_perm_bits_set() {
7167         let chanmon_cfgs = create_chanmon_cfgs(3);
7168         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7169         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7170         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7171         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7172         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7173
7174         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100_000);
7175
7176         // First hop
7177         let mut payment_event = {
7178                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
7179                 check_added_monitors!(nodes[0], 1);
7180                 SendEvent::from_node(&nodes[0])
7181         };
7182
7183         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7184         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7185         expect_pending_htlcs_forwardable!(nodes[1]);
7186         check_added_monitors!(nodes[1], 1);
7187         payment_event = SendEvent::from_node(&nodes[1]);
7188         assert_eq!(payment_event.msgs.len(), 1);
7189
7190         // Second Hop
7191         payment_event.msgs[0].onion_routing_packet.version = 1; // Trigger an invalid_onion_version error
7192         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
7193         check_added_monitors!(nodes[2], 0);
7194         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
7195
7196         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
7197         assert_eq!(events_3.len(), 1);
7198         match events_3[0] {
7199                 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
7200                         let mut update_msg = updates.update_fail_malformed_htlcs[0].clone();
7201                         // Set the NODE bit (BADONION and PERM already set in invalid_onion_version error)
7202                         update_msg.failure_code |= 0x2000;
7203
7204                         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg);
7205                         commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true);
7206                 },
7207                 _ => panic!("Unexpected event"),
7208         }
7209
7210         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
7211                 vec![HTLCDestination::NextHopChannel {
7212                         node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
7213         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
7214         assert_eq!(events_4.len(), 1);
7215         check_added_monitors!(nodes[1], 1);
7216
7217         match events_4[0] {
7218                 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
7219                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
7220                         commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
7221                 },
7222                 _ => panic!("Unexpected event"),
7223         }
7224
7225         let events_5 = nodes[0].node.get_and_clear_pending_events();
7226         assert_eq!(events_5.len(), 1);
7227
7228         // Expect a PaymentPathFailed event with a ChannelFailure network update for the channel between
7229         // the node originating the error to its next hop.
7230         match events_5[0] {
7231                 Event::PaymentPathFailed { network_update:
7232                         Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent }), error_code, ..
7233                 } => {
7234                         assert_eq!(short_channel_id, chan_2.0.contents.short_channel_id);
7235                         assert!(is_permanent);
7236                         assert_eq!(error_code, Some(0x8000|0x4000|0x2000|4));
7237                 },
7238                 _ => panic!("Unexpected event"),
7239         }
7240
7241         // TODO: Test actual removal of channel from NetworkGraph when it's implemented.
7242 }
7243
7244 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
7245         // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
7246         // 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
7247         // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
7248
7249         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7250         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7251         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7252         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7253         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7254         let chan =create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7255
7256         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7257
7258         // We route 2 dust-HTLCs between A and B
7259         let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7260         let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7261         route_payment(&nodes[0], &[&nodes[1]], 1000000);
7262
7263         // Cache one local commitment tx as previous
7264         let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7265
7266         // Fail one HTLC to prune it in the will-be-latest-local commitment tx
7267         nodes[1].node.fail_htlc_backwards(&payment_hash_2);
7268         check_added_monitors!(nodes[1], 0);
7269         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
7270         check_added_monitors!(nodes[1], 1);
7271
7272         let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7273         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
7274         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
7275         check_added_monitors!(nodes[0], 1);
7276
7277         // Cache one local commitment tx as lastest
7278         let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7279
7280         let events = nodes[0].node.get_and_clear_pending_msg_events();
7281         match events[0] {
7282                 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
7283                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7284                 },
7285                 _ => panic!("Unexpected event"),
7286         }
7287         match events[1] {
7288                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
7289                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7290                 },
7291                 _ => panic!("Unexpected event"),
7292         }
7293
7294         assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
7295         // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7296         if announce_latest {
7297                 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
7298         } else {
7299                 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
7300         }
7301
7302         check_closed_broadcast!(nodes[0], true);
7303         check_added_monitors!(nodes[0], 1);
7304         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7305
7306         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7307         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7308         let events = nodes[0].node.get_and_clear_pending_events();
7309         // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
7310         assert_eq!(events.len(), 2);
7311         let mut first_failed = false;
7312         for event in events {
7313                 match event {
7314                         Event::PaymentPathFailed { payment_hash, .. } => {
7315                                 if payment_hash == payment_hash_1 {
7316                                         assert!(!first_failed);
7317                                         first_failed = true;
7318                                 } else {
7319                                         assert_eq!(payment_hash, payment_hash_2);
7320                                 }
7321                         }
7322                         _ => panic!("Unexpected event"),
7323                 }
7324         }
7325 }
7326
7327 #[test]
7328 fn test_failure_delay_dust_htlc_local_commitment() {
7329         do_test_failure_delay_dust_htlc_local_commitment(true);
7330         do_test_failure_delay_dust_htlc_local_commitment(false);
7331 }
7332
7333 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7334         // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7335         // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7336         // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7337         // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7338         // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7339         // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7340
7341         let chanmon_cfgs = create_chanmon_cfgs(3);
7342         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7343         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7344         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7345         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7346
7347         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7348
7349         let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7350         let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7351
7352         let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7353         let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7354
7355         // We revoked bs_commitment_tx
7356         if revoked {
7357                 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7358                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
7359         }
7360
7361         let mut timeout_tx = Vec::new();
7362         if local {
7363                 // We fail dust-HTLC 1 by broadcast of local commitment tx
7364                 mine_transaction(&nodes[0], &as_commitment_tx[0]);
7365                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7366                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7367                 expect_payment_failed!(nodes[0], dust_hash, false);
7368
7369                 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
7370                 check_closed_broadcast!(nodes[0], true);
7371                 check_added_monitors!(nodes[0], 1);
7372                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7373                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
7374                 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7375                 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7376                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7377                 mine_transaction(&nodes[0], &timeout_tx[0]);
7378                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7379                 expect_payment_failed!(nodes[0], non_dust_hash, false);
7380         } else {
7381                 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7382                 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
7383                 check_closed_broadcast!(nodes[0], true);
7384                 check_added_monitors!(nodes[0], 1);
7385                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7386                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7387
7388                 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7389                 timeout_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().drain(..)
7390                         .filter(|tx| tx.input[0].previous_output.txid == bs_commitment_tx[0].txid()).collect();
7391                 check_spends!(timeout_tx[0], bs_commitment_tx[0]);
7392                 // For both a revoked or non-revoked commitment transaction, after ANTI_REORG_DELAY the
7393                 // dust HTLC should have been failed.
7394                 expect_payment_failed!(nodes[0], dust_hash, false);
7395
7396                 if !revoked {
7397                         assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7398                 } else {
7399                         assert_eq!(timeout_tx[0].lock_time.0, 0);
7400                 }
7401                 // We fail non-dust-HTLC 2 by broadcast of local timeout/revocation-claim tx
7402                 mine_transaction(&nodes[0], &timeout_tx[0]);
7403                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7404                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7405                 expect_payment_failed!(nodes[0], non_dust_hash, false);
7406         }
7407 }
7408
7409 #[test]
7410 fn test_sweep_outbound_htlc_failure_update() {
7411         do_test_sweep_outbound_htlc_failure_update(false, true);
7412         do_test_sweep_outbound_htlc_failure_update(false, false);
7413         do_test_sweep_outbound_htlc_failure_update(true, false);
7414 }
7415
7416 #[test]
7417 fn test_user_configurable_csv_delay() {
7418         // We test our channel constructors yield errors when we pass them absurd csv delay
7419
7420         let mut low_our_to_self_config = UserConfig::default();
7421         low_our_to_self_config.channel_handshake_config.our_to_self_delay = 6;
7422         let mut high_their_to_self_config = UserConfig::default();
7423         high_their_to_self_config.channel_handshake_limits.their_to_self_delay = 100;
7424         let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7425         let chanmon_cfgs = create_chanmon_cfgs(2);
7426         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7427         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7428         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7429
7430         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7431         if let Err(error) = Channel::new_outbound(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7432                 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &channelmanager::provided_init_features(), 1000000, 1000000, 0,
7433                 &low_our_to_self_config, 0, 42)
7434         {
7435                 match error {
7436                         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())); },
7437                         _ => panic!("Unexpected event"),
7438                 }
7439         } else { assert!(false) }
7440
7441         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7442         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7443         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7444         open_channel.to_self_delay = 200;
7445         if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7446                 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &channelmanager::provided_init_features(), &open_channel, 0,
7447                 &low_our_to_self_config, 0, &nodes[0].logger, 42)
7448         {
7449                 match error {
7450                         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()));  },
7451                         _ => panic!("Unexpected event"),
7452                 }
7453         } else { assert!(false); }
7454
7455         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7456         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7457         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()));
7458         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7459         accept_channel.to_self_delay = 200;
7460         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_channel);
7461         let reason_msg;
7462         if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7463                 match action {
7464                         &ErrorAction::SendErrorMessage { ref msg } => {
7465                                 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()));
7466                                 reason_msg = msg.data.clone();
7467                         },
7468                         _ => { panic!(); }
7469                 }
7470         } else { panic!(); }
7471         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg });
7472
7473         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7474         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7475         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7476         open_channel.to_self_delay = 200;
7477         if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7478                 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &channelmanager::provided_init_features(), &open_channel, 0,
7479                 &high_their_to_self_config, 0, &nodes[0].logger, 42)
7480         {
7481                 match error {
7482                         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())); },
7483                         _ => panic!("Unexpected event"),
7484                 }
7485         } else { assert!(false); }
7486 }
7487
7488 fn do_test_data_loss_protect(reconnect_panicing: bool) {
7489         // When we get a data_loss_protect proving we're behind, we immediately panic as the
7490         // chain::Watch API requirements have been violated (e.g. the user restored from a backup). The
7491         // panic message informs the user they should force-close without broadcasting, which is tested
7492         // if `reconnect_panicing` is not set.
7493         let persister;
7494         let logger;
7495         let fee_estimator;
7496         let tx_broadcaster;
7497         let chain_source;
7498         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7499         // We broadcast during Drop because chanmon is out of sync with chanmgr, which would cause a panic
7500         // during signing due to revoked tx
7501         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7502         let keys_manager = &chanmon_cfgs[0].keys_manager;
7503         let monitor;
7504         let node_state_0;
7505         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7506         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7507         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7508
7509         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7510
7511         // Cache node A state before any channel update
7512         let previous_node_state = nodes[0].node.encode();
7513         let mut previous_chain_monitor_state = test_utils::TestVecWriter(Vec::new());
7514         get_monitor!(nodes[0], chan.2).write(&mut previous_chain_monitor_state).unwrap();
7515
7516         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7517         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7518
7519         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7520         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7521
7522         // Restore node A from previous state
7523         logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7524         let mut chain_monitor = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut io::Cursor::new(previous_chain_monitor_state.0), keys_manager).unwrap().1;
7525         chain_source = test_utils::TestChainSource::new(Network::Testnet);
7526         tx_broadcaster = test_utils::TestBroadcaster { txn_broadcasted: Mutex::new(Vec::new()), blocks: Arc::new(Mutex::new(Vec::new())) };
7527         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
7528         persister = test_utils::TestPersister::new();
7529         monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &tx_broadcaster, &logger, &fee_estimator, &persister, keys_manager);
7530         node_state_0 = {
7531                 let mut channel_monitors = HashMap::new();
7532                 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chain_monitor);
7533                 <(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 {
7534                         keys_manager: keys_manager,
7535                         fee_estimator: &fee_estimator,
7536                         chain_monitor: &monitor,
7537                         logger: &logger,
7538                         tx_broadcaster: &tx_broadcaster,
7539                         default_config: UserConfig::default(),
7540                         channel_monitors,
7541                 }).unwrap().1
7542         };
7543         nodes[0].node = &node_state_0;
7544         assert_eq!(monitor.watch_channel(OutPoint { txid: chan.3.txid(), index: 0 }, chain_monitor),
7545                 ChannelMonitorUpdateStatus::Completed);
7546         nodes[0].chain_monitor = &monitor;
7547         nodes[0].chain_source = &chain_source;
7548
7549         check_added_monitors!(nodes[0], 1);
7550
7551         if reconnect_panicing {
7552                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
7553                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
7554
7555                 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7556
7557                 // Check we close channel detecting A is fallen-behind
7558                 // Check that we sent the warning message when we detected that A has fallen behind,
7559                 // and give the possibility for A to recover from the warning.
7560                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7561                 let warn_msg = "Peer attempted to reestablish channel with a very old local commitment transaction".to_owned();
7562                 assert!(check_warn_msg!(nodes[1], nodes[0].node.get_our_node_id(), chan.2).contains(&warn_msg));
7563
7564                 {
7565                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7566                         // The node B should not broadcast the transaction to force close the channel!
7567                         assert!(node_txn.is_empty());
7568                 }
7569
7570                 let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7571                 // Check A panics upon seeing proof it has fallen behind.
7572                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7573                 return; // By this point we should have panic'ed!
7574         }
7575
7576         nodes[0].node.force_close_without_broadcasting_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
7577         check_added_monitors!(nodes[0], 1);
7578         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
7579         {
7580                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7581                 assert_eq!(node_txn.len(), 0);
7582         }
7583
7584         for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7585                 if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7586                 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7587                         match action {
7588                                 &ErrorAction::SendErrorMessage { ref msg } => {
7589                                         assert_eq!(msg.data, "Channel force-closed");
7590                                 },
7591                                 _ => panic!("Unexpected event!"),
7592                         }
7593                 } else {
7594                         panic!("Unexpected event {:?}", msg)
7595                 }
7596         }
7597
7598         // after the warning message sent by B, we should not able to
7599         // use the channel, or reconnect with success to the channel.
7600         assert!(nodes[0].node.list_usable_channels().is_empty());
7601         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
7602         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
7603         let retry_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7604
7605         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &retry_reestablish[0]);
7606         let mut err_msgs_0 = Vec::with_capacity(1);
7607         for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7608                 if let MessageSendEvent::HandleError { ref action, .. } = msg {
7609                         match action {
7610                                 &ErrorAction::SendErrorMessage { ref msg } => {
7611                                         assert_eq!(msg.data, "Failed to find corresponding channel");
7612                                         err_msgs_0.push(msg.clone());
7613                                 },
7614                                 _ => panic!("Unexpected event!"),
7615                         }
7616                 } else {
7617                         panic!("Unexpected event!");
7618                 }
7619         }
7620         assert_eq!(err_msgs_0.len(), 1);
7621         nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), &err_msgs_0[0]);
7622         assert!(nodes[1].node.list_usable_channels().is_empty());
7623         check_added_monitors!(nodes[1], 1);
7624         check_closed_event!(nodes[1], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "Failed to find corresponding channel".to_owned() });
7625         check_closed_broadcast!(nodes[1], false);
7626 }
7627
7628 #[test]
7629 #[should_panic]
7630 fn test_data_loss_protect_showing_stale_state_panics() {
7631         do_test_data_loss_protect(true);
7632 }
7633
7634 #[test]
7635 fn test_force_close_without_broadcast() {
7636         do_test_data_loss_protect(false);
7637 }
7638
7639 #[test]
7640 fn test_check_htlc_underpaying() {
7641         // Send payment through A -> B but A is maliciously
7642         // sending a probe payment (i.e less than expected value0
7643         // to B, B should refuse payment.
7644
7645         let chanmon_cfgs = create_chanmon_cfgs(2);
7646         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7647         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7648         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7649
7650         // Create some initial channels
7651         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7652
7653         let scorer = test_utils::TestScorer::with_penalty(0);
7654         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7655         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id()).with_features(channelmanager::provided_invoice_features());
7656         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();
7657         let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7658         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200).unwrap();
7659         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
7660         check_added_monitors!(nodes[0], 1);
7661
7662         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7663         assert_eq!(events.len(), 1);
7664         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7665         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7666         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7667
7668         // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7669         // and then will wait a second random delay before failing the HTLC back:
7670         expect_pending_htlcs_forwardable!(nodes[1]);
7671         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
7672
7673         // Node 3 is expecting payment of 100_000 but received 10_000,
7674         // it should fail htlc like we didn't know the preimage.
7675         nodes[1].node.process_pending_htlc_forwards();
7676
7677         let events = nodes[1].node.get_and_clear_pending_msg_events();
7678         assert_eq!(events.len(), 1);
7679         let (update_fail_htlc, commitment_signed) = match events[0] {
7680                 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 } } => {
7681                         assert!(update_add_htlcs.is_empty());
7682                         assert!(update_fulfill_htlcs.is_empty());
7683                         assert_eq!(update_fail_htlcs.len(), 1);
7684                         assert!(update_fail_malformed_htlcs.is_empty());
7685                         assert!(update_fee.is_none());
7686                         (update_fail_htlcs[0].clone(), commitment_signed)
7687                 },
7688                 _ => panic!("Unexpected event"),
7689         };
7690         check_added_monitors!(nodes[1], 1);
7691
7692         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7693         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7694
7695         // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7696         let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7697         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(CHAN_CONFIRM_DEPTH));
7698         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7699 }
7700
7701 #[test]
7702 fn test_announce_disable_channels() {
7703         // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7704         // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7705
7706         let chanmon_cfgs = create_chanmon_cfgs(2);
7707         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7708         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7709         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7710
7711         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7712         create_announced_chan_between_nodes(&nodes, 1, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7713         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7714
7715         // Disconnect peers
7716         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7717         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7718
7719         nodes[0].node.timer_tick_occurred(); // Enabled -> DisabledStaged
7720         nodes[0].node.timer_tick_occurred(); // DisabledStaged -> Disabled
7721         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7722         assert_eq!(msg_events.len(), 3);
7723         let mut chans_disabled = HashMap::new();
7724         for e in msg_events {
7725                 match e {
7726                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7727                                 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7728                                 // Check that each channel gets updated exactly once
7729                                 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7730                                         panic!("Generated ChannelUpdate for wrong chan!");
7731                                 }
7732                         },
7733                         _ => panic!("Unexpected event"),
7734                 }
7735         }
7736         // Reconnect peers
7737         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
7738         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7739         assert_eq!(reestablish_1.len(), 3);
7740         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
7741         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7742         assert_eq!(reestablish_2.len(), 3);
7743
7744         // Reestablish chan_1
7745         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7746         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7747         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7748         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7749         // Reestablish chan_2
7750         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7751         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7752         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7753         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7754         // Reestablish chan_3
7755         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7756         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7757         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7758         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7759
7760         nodes[0].node.timer_tick_occurred();
7761         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7762         nodes[0].node.timer_tick_occurred();
7763         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7764         assert_eq!(msg_events.len(), 3);
7765         for e in msg_events {
7766                 match e {
7767                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7768                                 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7769                                 match chans_disabled.remove(&msg.contents.short_channel_id) {
7770                                         // Each update should have a higher timestamp than the previous one, replacing
7771                                         // the old one.
7772                                         Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7773                                         None => panic!("Generated ChannelUpdate for wrong chan!"),
7774                                 }
7775                         },
7776                         _ => panic!("Unexpected event"),
7777                 }
7778         }
7779         // Check that each channel gets updated exactly once
7780         assert!(chans_disabled.is_empty());
7781 }
7782
7783 #[test]
7784 fn test_bump_penalty_txn_on_revoked_commitment() {
7785         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7786         // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7787
7788         let chanmon_cfgs = create_chanmon_cfgs(2);
7789         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7790         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7791         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7792
7793         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7794
7795         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7796         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id())
7797                 .with_features(channelmanager::provided_invoice_features());
7798         let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000, 30);
7799         send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7800
7801         let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7802         // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7803         assert_eq!(revoked_txn[0].output.len(), 4);
7804         assert_eq!(revoked_txn[0].input.len(), 1);
7805         assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7806         let revoked_txid = revoked_txn[0].txid();
7807
7808         let mut penalty_sum = 0;
7809         for outp in revoked_txn[0].output.iter() {
7810                 if outp.script_pubkey.is_v0_p2wsh() {
7811                         penalty_sum += outp.value;
7812                 }
7813         }
7814
7815         // Connect blocks to change height_timer range to see if we use right soonest_timelock
7816         let header_114 = connect_blocks(&nodes[1], 14);
7817
7818         // Actually revoke tx by claiming a HTLC
7819         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7820         let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7821         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] });
7822         check_added_monitors!(nodes[1], 1);
7823
7824         // One or more justice tx should have been broadcast, check it
7825         let penalty_1;
7826         let feerate_1;
7827         {
7828                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7829                 assert_eq!(node_txn.len(), 2); // justice tx (broadcasted from ChannelMonitor) + local commitment tx
7830                 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7831                 assert_eq!(node_txn[0].output.len(), 1);
7832                 check_spends!(node_txn[0], revoked_txn[0]);
7833                 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7834                 feerate_1 = fee_1 * 1000 / node_txn[0].weight() as u64;
7835                 penalty_1 = node_txn[0].txid();
7836                 node_txn.clear();
7837         };
7838
7839         // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7840         connect_blocks(&nodes[1], 15);
7841         let mut penalty_2 = penalty_1;
7842         let mut feerate_2 = 0;
7843         {
7844                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7845                 assert_eq!(node_txn.len(), 1);
7846                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7847                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7848                         assert_eq!(node_txn[0].output.len(), 1);
7849                         check_spends!(node_txn[0], revoked_txn[0]);
7850                         penalty_2 = node_txn[0].txid();
7851                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7852                         assert_ne!(penalty_2, penalty_1);
7853                         let fee_2 = penalty_sum - node_txn[0].output[0].value;
7854                         feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7855                         // Verify 25% bump heuristic
7856                         assert!(feerate_2 * 100 >= feerate_1 * 125);
7857                         node_txn.clear();
7858                 }
7859         }
7860         assert_ne!(feerate_2, 0);
7861
7862         // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7863         connect_blocks(&nodes[1], 1);
7864         let penalty_3;
7865         let mut feerate_3 = 0;
7866         {
7867                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7868                 assert_eq!(node_txn.len(), 1);
7869                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7870                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7871                         assert_eq!(node_txn[0].output.len(), 1);
7872                         check_spends!(node_txn[0], revoked_txn[0]);
7873                         penalty_3 = node_txn[0].txid();
7874                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7875                         assert_ne!(penalty_3, penalty_2);
7876                         let fee_3 = penalty_sum - node_txn[0].output[0].value;
7877                         feerate_3 = fee_3 * 1000 / node_txn[0].weight() as u64;
7878                         // Verify 25% bump heuristic
7879                         assert!(feerate_3 * 100 >= feerate_2 * 125);
7880                         node_txn.clear();
7881                 }
7882         }
7883         assert_ne!(feerate_3, 0);
7884
7885         nodes[1].node.get_and_clear_pending_events();
7886         nodes[1].node.get_and_clear_pending_msg_events();
7887 }
7888
7889 #[test]
7890 fn test_bump_penalty_txn_on_revoked_htlcs() {
7891         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7892         // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7893
7894         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7895         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7896         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7897         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7898         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7899
7900         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7901         // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7902         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id()).with_features(channelmanager::provided_invoice_features());
7903         let scorer = test_utils::TestScorer::with_penalty(0);
7904         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7905         let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None,
7906                 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7907         let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7908         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id()).with_features(channelmanager::provided_invoice_features());
7909         let route = get_route(&nodes[1].node.get_our_node_id(), &payment_params, &nodes[1].network_graph.read_only(), None,
7910                 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7911         send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7912
7913         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7914         assert_eq!(revoked_local_txn[0].input.len(), 1);
7915         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7916
7917         // Revoke local commitment tx
7918         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7919
7920         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7921         // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7922         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] });
7923         check_closed_broadcast!(nodes[1], true);
7924         check_added_monitors!(nodes[1], 1);
7925         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7926         connect_blocks(&nodes[1], 49); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7927
7928         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
7929         assert_eq!(revoked_htlc_txn.len(), 3);
7930         check_spends!(revoked_htlc_txn[1], chan.3);
7931
7932         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7933         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7934         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7935
7936         assert_eq!(revoked_htlc_txn[2].input.len(), 1);
7937         assert_eq!(revoked_htlc_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7938         assert_eq!(revoked_htlc_txn[2].output.len(), 1);
7939         check_spends!(revoked_htlc_txn[2], revoked_local_txn[0]);
7940
7941         // Broadcast set of revoked txn on A
7942         let hash_128 = connect_blocks(&nodes[0], 40);
7943         let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7944         connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] });
7945         let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7946         connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[2].clone()] });
7947         let events = nodes[0].node.get_and_clear_pending_events();
7948         expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7949         match events.last().unwrap() {
7950                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7951                 _ => panic!("Unexpected event"),
7952         }
7953         let first;
7954         let feerate_1;
7955         let penalty_txn;
7956         {
7957                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7958                 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7959                 // Verify claim tx are spending revoked HTLC txn
7960
7961                 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7962                 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7963                 // which are included in the same block (they are broadcasted because we scan the
7964                 // transactions linearly and generate claims as we go, they likely should be removed in the
7965                 // future).
7966                 assert_eq!(node_txn[0].input.len(), 1);
7967                 check_spends!(node_txn[0], revoked_local_txn[0]);
7968                 assert_eq!(node_txn[1].input.len(), 1);
7969                 check_spends!(node_txn[1], revoked_local_txn[0]);
7970                 assert_eq!(node_txn[2].input.len(), 1);
7971                 check_spends!(node_txn[2], revoked_local_txn[0]);
7972
7973                 // Each of the three justice transactions claim a separate (single) output of the three
7974                 // available, which we check here:
7975                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7976                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7977                 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7978
7979                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7980                 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7981
7982                 // node_txn[3] is the local commitment tx broadcast just because (and somewhat in case of
7983                 // reorgs, though its not clear its ever worth broadcasting conflicting txn like this when
7984                 // a remote commitment tx has already been confirmed).
7985                 check_spends!(node_txn[3], chan.3);
7986
7987                 // node_txn[4] spends the revoked outputs from the revoked_htlc_txn (which only have one
7988                 // output, checked above).
7989                 assert_eq!(node_txn[4].input.len(), 2);
7990                 assert_eq!(node_txn[4].output.len(), 1);
7991                 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7992
7993                 first = node_txn[4].txid();
7994                 // Store both feerates for later comparison
7995                 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[4].output[0].value;
7996                 feerate_1 = fee_1 * 1000 / node_txn[4].weight() as u64;
7997                 penalty_txn = vec![node_txn[2].clone()];
7998                 node_txn.clear();
7999         }
8000
8001         // Connect one more block to see if bumped penalty are issued for HTLC txn
8002         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8003         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
8004         let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8005         connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() });
8006         {
8007                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8008                 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
8009
8010                 check_spends!(node_txn[0], revoked_local_txn[0]);
8011                 check_spends!(node_txn[1], revoked_local_txn[0]);
8012                 // Note that these are both bogus - they spend outputs already claimed in block 129:
8013                 if node_txn[0].input[0].previous_output == revoked_htlc_txn[0].input[0].previous_output  {
8014                         assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
8015                 } else {
8016                         assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
8017                         assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
8018                 }
8019
8020                 node_txn.clear();
8021         };
8022
8023         // Few more blocks to confirm penalty txn
8024         connect_blocks(&nodes[0], 4);
8025         assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
8026         let header_144 = connect_blocks(&nodes[0], 9);
8027         let node_txn = {
8028                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8029                 assert_eq!(node_txn.len(), 1);
8030
8031                 assert_eq!(node_txn[0].input.len(), 2);
8032                 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[2]);
8033                 // Verify bumped tx is different and 25% bump heuristic
8034                 assert_ne!(first, node_txn[0].txid());
8035                 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[0].output[0].value;
8036                 let feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
8037                 assert!(feerate_2 * 100 > feerate_1 * 125);
8038                 let txn = vec![node_txn[0].clone()];
8039                 node_txn.clear();
8040                 txn
8041         };
8042         // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
8043         let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8044         connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn });
8045         connect_blocks(&nodes[0], 20);
8046         {
8047                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8048                 // We verify than no new transaction has been broadcast because previously
8049                 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
8050                 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
8051                 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
8052                 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
8053                 // up bumped justice generation.
8054                 assert_eq!(node_txn.len(), 0);
8055                 node_txn.clear();
8056         }
8057         check_closed_broadcast!(nodes[0], true);
8058         check_added_monitors!(nodes[0], 1);
8059 }
8060
8061 #[test]
8062 fn test_bump_penalty_txn_on_remote_commitment() {
8063         // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
8064         // we're able to claim outputs on remote commitment transaction before timelocks expiration
8065
8066         // Create 2 HTLCs
8067         // Provide preimage for one
8068         // Check aggregation
8069
8070         let chanmon_cfgs = create_chanmon_cfgs(2);
8071         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8072         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8073         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8074
8075         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8076         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
8077         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
8078
8079         // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
8080         let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
8081         assert_eq!(remote_txn[0].output.len(), 4);
8082         assert_eq!(remote_txn[0].input.len(), 1);
8083         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
8084
8085         // Claim a HTLC without revocation (provide B monitor with preimage)
8086         nodes[1].node.claim_funds(payment_preimage);
8087         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
8088         mine_transaction(&nodes[1], &remote_txn[0]);
8089         check_added_monitors!(nodes[1], 2);
8090         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
8091
8092         // One or more claim tx should have been broadcast, check it
8093         let timeout;
8094         let preimage;
8095         let preimage_bump;
8096         let feerate_timeout;
8097         let feerate_preimage;
8098         {
8099                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8100                 // 5 transactions including:
8101                 //   local commitment + HTLC-Success
8102                 //   preimage and timeout sweeps from remote commitment + preimage sweep bump
8103                 assert_eq!(node_txn.len(), 5);
8104                 assert_eq!(node_txn[0].input.len(), 1);
8105                 assert_eq!(node_txn[3].input.len(), 1);
8106                 assert_eq!(node_txn[4].input.len(), 1);
8107                 check_spends!(node_txn[0], remote_txn[0]);
8108                 check_spends!(node_txn[3], remote_txn[0]);
8109                 check_spends!(node_txn[4], remote_txn[0]);
8110
8111                 check_spends!(node_txn[1], chan.3); // local commitment
8112                 check_spends!(node_txn[2], node_txn[1]); // local HTLC-Success
8113
8114                 preimage = node_txn[0].txid();
8115                 let index = node_txn[0].input[0].previous_output.vout;
8116                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8117                 feerate_preimage = fee * 1000 / node_txn[0].weight() as u64;
8118
8119                 let (preimage_bump_tx, timeout_tx) = if node_txn[3].input[0].previous_output == node_txn[0].input[0].previous_output {
8120                         (node_txn[3].clone(), node_txn[4].clone())
8121                 } else {
8122                         (node_txn[4].clone(), node_txn[3].clone())
8123                 };
8124
8125                 preimage_bump = preimage_bump_tx;
8126                 check_spends!(preimage_bump, remote_txn[0]);
8127                 assert_eq!(node_txn[0].input[0].previous_output, preimage_bump.input[0].previous_output);
8128
8129                 timeout = timeout_tx.txid();
8130                 let index = timeout_tx.input[0].previous_output.vout;
8131                 let fee = remote_txn[0].output[index as usize].value - timeout_tx.output[0].value;
8132                 feerate_timeout = fee * 1000 / timeout_tx.weight() as u64;
8133
8134                 node_txn.clear();
8135         };
8136         assert_ne!(feerate_timeout, 0);
8137         assert_ne!(feerate_preimage, 0);
8138
8139         // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
8140         connect_blocks(&nodes[1], 15);
8141         {
8142                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8143                 assert_eq!(node_txn.len(), 1);
8144                 assert_eq!(node_txn[0].input.len(), 1);
8145                 assert_eq!(preimage_bump.input.len(), 1);
8146                 check_spends!(node_txn[0], remote_txn[0]);
8147                 check_spends!(preimage_bump, remote_txn[0]);
8148
8149                 let index = preimage_bump.input[0].previous_output.vout;
8150                 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
8151                 let new_feerate = fee * 1000 / preimage_bump.weight() as u64;
8152                 assert!(new_feerate * 100 > feerate_timeout * 125);
8153                 assert_ne!(timeout, preimage_bump.txid());
8154
8155                 let index = node_txn[0].input[0].previous_output.vout;
8156                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8157                 let new_feerate = fee * 1000 / node_txn[0].weight() as u64;
8158                 assert!(new_feerate * 100 > feerate_preimage * 125);
8159                 assert_ne!(preimage, node_txn[0].txid());
8160
8161                 node_txn.clear();
8162         }
8163
8164         nodes[1].node.get_and_clear_pending_events();
8165         nodes[1].node.get_and_clear_pending_msg_events();
8166 }
8167
8168 #[test]
8169 fn test_counterparty_raa_skip_no_crash() {
8170         // Previously, if our counterparty sent two RAAs in a row without us having provided a
8171         // commitment transaction, we would have happily carried on and provided them the next
8172         // commitment transaction based on one RAA forward. This would probably eventually have led to
8173         // channel closure, but it would not have resulted in funds loss. Still, our
8174         // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
8175         // check simply that the channel is closed in response to such an RAA, but don't check whether
8176         // we decide to punish our counterparty for revoking their funds (as we don't currently
8177         // implement that).
8178         let chanmon_cfgs = create_chanmon_cfgs(2);
8179         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8180         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8181         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8182         let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
8183
8184         let per_commitment_secret;
8185         let next_per_commitment_point;
8186         {
8187                 let mut guard = nodes[0].node.channel_state.lock().unwrap();
8188                 let keys = guard.by_id.get_mut(&channel_id).unwrap().get_signer();
8189
8190                 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
8191
8192                 // Make signer believe we got a counterparty signature, so that it allows the revocation
8193                 keys.get_enforcement_state().last_holder_commitment -= 1;
8194                 per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
8195
8196                 // Must revoke without gaps
8197                 keys.get_enforcement_state().last_holder_commitment -= 1;
8198                 keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
8199
8200                 keys.get_enforcement_state().last_holder_commitment -= 1;
8201                 next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
8202                         &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
8203         }
8204
8205         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
8206                 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
8207         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
8208         check_added_monitors!(nodes[1], 1);
8209         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
8210 }
8211
8212 #[test]
8213 fn test_bump_txn_sanitize_tracking_maps() {
8214         // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
8215         // verify we clean then right after expiration of ANTI_REORG_DELAY.
8216
8217         let chanmon_cfgs = create_chanmon_cfgs(2);
8218         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8219         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8220         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8221
8222         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8223         // Lock HTLC in both directions
8224         let (payment_preimage_1, _, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000);
8225         let (_, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000);
8226
8227         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
8228         assert_eq!(revoked_local_txn[0].input.len(), 1);
8229         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8230
8231         // Revoke local commitment tx
8232         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
8233
8234         // Broadcast set of revoked txn on A
8235         connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
8236         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[0], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
8237         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
8238
8239         mine_transaction(&nodes[0], &revoked_local_txn[0]);
8240         check_closed_broadcast!(nodes[0], true);
8241         check_added_monitors!(nodes[0], 1);
8242         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8243         let penalty_txn = {
8244                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8245                 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
8246                 check_spends!(node_txn[0], revoked_local_txn[0]);
8247                 check_spends!(node_txn[1], revoked_local_txn[0]);
8248                 check_spends!(node_txn[2], revoked_local_txn[0]);
8249                 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
8250                 node_txn.clear();
8251                 penalty_txn
8252         };
8253         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8254         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
8255         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8256         {
8257                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
8258                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
8259                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
8260         }
8261 }
8262
8263 #[test]
8264 fn test_pending_claimed_htlc_no_balance_underflow() {
8265         // Tests that if we have a pending outbound HTLC as well as a claimed-but-not-fully-removed
8266         // HTLC we will not underflow when we call `Channel::get_balance_msat()`.
8267         let chanmon_cfgs = create_chanmon_cfgs(2);
8268         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8269         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8270         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8271         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8272
8273         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_010_000);
8274         nodes[1].node.claim_funds(payment_preimage);
8275         expect_payment_claimed!(nodes[1], payment_hash, 1_010_000);
8276         check_added_monitors!(nodes[1], 1);
8277         let fulfill_ev = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8278
8279         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &fulfill_ev.update_fulfill_htlcs[0]);
8280         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
8281         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &fulfill_ev.commitment_signed);
8282         check_added_monitors!(nodes[0], 1);
8283         let (_raa, _cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
8284
8285         // At this point nodes[1] has received 1,010k msat (10k msat more than their reserve) and can
8286         // send an HTLC back (though it will go in the holding cell). Send an HTLC back and check we
8287         // can get our balance.
8288
8289         // Get a route from nodes[1] to nodes[0] by getting a route going the other way and then flip
8290         // the public key of the only hop. This works around ChannelDetails not showing the
8291         // almost-claimed HTLC as available balance.
8292         let (mut route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 10_000);
8293         route.payment_params = None; // This is all wrong, but unnecessary
8294         route.paths[0][0].pubkey = nodes[0].node.get_our_node_id();
8295         let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[0]);
8296         nodes[1].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
8297
8298         assert_eq!(nodes[1].node.list_channels()[0].balance_msat, 1_000_000);
8299 }
8300
8301 #[test]
8302 fn test_channel_conf_timeout() {
8303         // Tests that, for inbound channels, we give up on them if the funding transaction does not
8304         // confirm within 2016 blocks, as recommended by BOLT 2.
8305         let chanmon_cfgs = create_chanmon_cfgs(2);
8306         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8307         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8308         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8309
8310         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());
8311
8312         // The outbound node should wait forever for confirmation:
8313         // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
8314         // copied here instead of directly referencing the constant.
8315         connect_blocks(&nodes[0], 2016);
8316         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8317
8318         // The inbound node should fail the channel after exactly 2016 blocks
8319         connect_blocks(&nodes[1], 2015);
8320         check_added_monitors!(nodes[1], 0);
8321         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8322
8323         connect_blocks(&nodes[1], 1);
8324         check_added_monitors!(nodes[1], 1);
8325         check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut);
8326         let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
8327         assert_eq!(close_ev.len(), 1);
8328         match close_ev[0] {
8329                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
8330                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8331                         assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
8332                 },
8333                 _ => panic!("Unexpected event"),
8334         }
8335 }
8336
8337 #[test]
8338 fn test_override_channel_config() {
8339         let chanmon_cfgs = create_chanmon_cfgs(2);
8340         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8341         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8342         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8343
8344         // Node0 initiates a channel to node1 using the override config.
8345         let mut override_config = UserConfig::default();
8346         override_config.channel_handshake_config.our_to_self_delay = 200;
8347
8348         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
8349
8350         // Assert the channel created by node0 is using the override config.
8351         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8352         assert_eq!(res.channel_flags, 0);
8353         assert_eq!(res.to_self_delay, 200);
8354 }
8355
8356 #[test]
8357 fn test_override_0msat_htlc_minimum() {
8358         let mut zero_config = UserConfig::default();
8359         zero_config.channel_handshake_config.our_htlc_minimum_msat = 0;
8360         let chanmon_cfgs = create_chanmon_cfgs(2);
8361         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8362         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
8363         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8364
8365         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
8366         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8367         assert_eq!(res.htlc_minimum_msat, 1);
8368
8369         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &res);
8370         let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8371         assert_eq!(res.htlc_minimum_msat, 1);
8372 }
8373
8374 #[test]
8375 fn test_channel_update_has_correct_htlc_maximum_msat() {
8376         // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
8377         // Bolt 7 specifies that if present `htlc_maximum_msat`:
8378         // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
8379         // 90% of the `channel_value`.
8380         // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
8381
8382         let mut config_30_percent = UserConfig::default();
8383         config_30_percent.channel_handshake_config.announced_channel = true;
8384         config_30_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
8385         let mut config_50_percent = UserConfig::default();
8386         config_50_percent.channel_handshake_config.announced_channel = true;
8387         config_50_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
8388         let mut config_95_percent = UserConfig::default();
8389         config_95_percent.channel_handshake_config.announced_channel = true;
8390         config_95_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
8391         let mut config_100_percent = UserConfig::default();
8392         config_100_percent.channel_handshake_config.announced_channel = true;
8393         config_100_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
8394
8395         let chanmon_cfgs = create_chanmon_cfgs(4);
8396         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8397         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)]);
8398         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8399
8400         let channel_value_satoshis = 100000;
8401         let channel_value_msat = channel_value_satoshis * 1000;
8402         let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
8403         let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
8404         let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
8405
8406         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());
8407         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());
8408
8409         // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
8410         // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
8411         assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, channel_value_50_percent_msat);
8412         // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
8413         // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
8414         assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, channel_value_30_percent_msat);
8415
8416         // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
8417         // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
8418         // `channel_value`.
8419         assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
8420         // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
8421         // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
8422         // `channel_value`.
8423         assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
8424 }
8425
8426 #[test]
8427 fn test_manually_accept_inbound_channel_request() {
8428         let mut manually_accept_conf = UserConfig::default();
8429         manually_accept_conf.manually_accept_inbound_channels = true;
8430         let chanmon_cfgs = create_chanmon_cfgs(2);
8431         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8432         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8433         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8434
8435         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8436         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8437
8438         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &res);
8439
8440         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8441         // accepting the inbound channel request.
8442         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8443
8444         let events = nodes[1].node.get_and_clear_pending_events();
8445         match events[0] {
8446                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8447                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
8448                 }
8449                 _ => panic!("Unexpected event"),
8450         }
8451
8452         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8453         assert_eq!(accept_msg_ev.len(), 1);
8454
8455         match accept_msg_ev[0] {
8456                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8457                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8458                 }
8459                 _ => panic!("Unexpected event"),
8460         }
8461
8462         nodes[1].node.force_close_broadcasting_latest_txn(&temp_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
8463
8464         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8465         assert_eq!(close_msg_ev.len(), 1);
8466
8467         let events = nodes[1].node.get_and_clear_pending_events();
8468         match events[0] {
8469                 Event::ChannelClosed { user_channel_id, .. } => {
8470                         assert_eq!(user_channel_id, 23);
8471                 }
8472                 _ => panic!("Unexpected event"),
8473         }
8474 }
8475
8476 #[test]
8477 fn test_manually_reject_inbound_channel_request() {
8478         let mut manually_accept_conf = UserConfig::default();
8479         manually_accept_conf.manually_accept_inbound_channels = true;
8480         let chanmon_cfgs = create_chanmon_cfgs(2);
8481         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8482         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8483         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8484
8485         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8486         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8487
8488         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &res);
8489
8490         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8491         // rejecting the inbound channel request.
8492         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8493
8494         let events = nodes[1].node.get_and_clear_pending_events();
8495         match events[0] {
8496                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8497                         nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
8498                 }
8499                 _ => panic!("Unexpected event"),
8500         }
8501
8502         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8503         assert_eq!(close_msg_ev.len(), 1);
8504
8505         match close_msg_ev[0] {
8506                 MessageSendEvent::HandleError { ref node_id, .. } => {
8507                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8508                 }
8509                 _ => panic!("Unexpected event"),
8510         }
8511         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
8512 }
8513
8514 #[test]
8515 fn test_reject_funding_before_inbound_channel_accepted() {
8516         // This tests that when `UserConfig::manually_accept_inbound_channels` is set to true, inbound
8517         // channels must to be manually accepted through `ChannelManager::accept_inbound_channel` by
8518         // the node operator before the counterparty sends a `FundingCreated` message. If a
8519         // `FundingCreated` message is received before the channel is accepted, it should be rejected
8520         // and the channel should be closed.
8521         let mut manually_accept_conf = UserConfig::default();
8522         manually_accept_conf.manually_accept_inbound_channels = true;
8523         let chanmon_cfgs = create_chanmon_cfgs(2);
8524         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8525         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8526         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8527
8528         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8529         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8530         let temp_channel_id = res.temporary_channel_id;
8531
8532         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &res);
8533
8534         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in the `msg_events`.
8535         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8536
8537         // Clear the `Event::OpenChannelRequest` event without responding to the request.
8538         nodes[1].node.get_and_clear_pending_events();
8539
8540         // Get the `AcceptChannel` message of `nodes[1]` without calling
8541         // `ChannelManager::accept_inbound_channel`, which generates a
8542         // `MessageSendEvent::SendAcceptChannel` event. The message is passed to `nodes[0]`
8543         // `handle_accept_channel`, which is required in order for `create_funding_transaction` to
8544         // succeed when `nodes[0]` is passed to it.
8545         let accept_chan_msg = {
8546                 let mut lock;
8547                 let channel = get_channel_ref!(&nodes[1], lock, temp_channel_id);
8548                 channel.get_accept_channel_message()
8549         };
8550         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_chan_msg);
8551
8552         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8553
8554         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8555         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8556
8557         // The `funding_created_msg` should be rejected by `nodes[1]` as it hasn't accepted the channel
8558         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8559
8560         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8561         assert_eq!(close_msg_ev.len(), 1);
8562
8563         let expected_err = "FundingCreated message received before the channel was accepted";
8564         match close_msg_ev[0] {
8565                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id, } => {
8566                         assert_eq!(msg.channel_id, temp_channel_id);
8567                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8568                         assert_eq!(msg.data, expected_err);
8569                 }
8570                 _ => panic!("Unexpected event"),
8571         }
8572
8573         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
8574 }
8575
8576 #[test]
8577 fn test_can_not_accept_inbound_channel_twice() {
8578         let mut manually_accept_conf = UserConfig::default();
8579         manually_accept_conf.manually_accept_inbound_channels = true;
8580         let chanmon_cfgs = create_chanmon_cfgs(2);
8581         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8582         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8583         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8584
8585         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8586         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8587
8588         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &res);
8589
8590         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8591         // accepting the inbound channel request.
8592         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8593
8594         let events = nodes[1].node.get_and_clear_pending_events();
8595         match events[0] {
8596                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8597                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
8598                         let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
8599                         match api_res {
8600                                 Err(APIError::APIMisuseError { err }) => {
8601                                         assert_eq!(err, "The channel isn't currently awaiting to be accepted.");
8602                                 },
8603                                 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
8604                                 Err(_) => panic!("Unexpected Error"),
8605                         }
8606                 }
8607                 _ => panic!("Unexpected event"),
8608         }
8609
8610         // Ensure that the channel wasn't closed after attempting to accept it twice.
8611         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8612         assert_eq!(accept_msg_ev.len(), 1);
8613
8614         match accept_msg_ev[0] {
8615                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8616                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8617                 }
8618                 _ => panic!("Unexpected event"),
8619         }
8620 }
8621
8622 #[test]
8623 fn test_can_not_accept_unknown_inbound_channel() {
8624         let chanmon_cfg = create_chanmon_cfgs(2);
8625         let node_cfg = create_node_cfgs(2, &chanmon_cfg);
8626         let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
8627         let nodes = create_network(2, &node_cfg, &node_chanmgr);
8628
8629         let unknown_channel_id = [0; 32];
8630         let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
8631         match api_res {
8632                 Err(APIError::ChannelUnavailable { err }) => {
8633                         assert_eq!(err, "Can't accept a channel that doesn't exist");
8634                 },
8635                 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
8636                 Err(_) => panic!("Unexpected Error"),
8637         }
8638 }
8639
8640 #[test]
8641 fn test_simple_mpp() {
8642         // Simple test of sending a multi-path payment.
8643         let chanmon_cfgs = create_chanmon_cfgs(4);
8644         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8645         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8646         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8647
8648         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;
8649         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;
8650         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;
8651         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;
8652
8653         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8654         let path = route.paths[0].clone();
8655         route.paths.push(path);
8656         route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8657         route.paths[0][0].short_channel_id = chan_1_id;
8658         route.paths[0][1].short_channel_id = chan_3_id;
8659         route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8660         route.paths[1][0].short_channel_id = chan_2_id;
8661         route.paths[1][1].short_channel_id = chan_4_id;
8662         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8663         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8664 }
8665
8666 #[test]
8667 fn test_preimage_storage() {
8668         // Simple test of payment preimage storage allowing no client-side storage to claim payments
8669         let chanmon_cfgs = create_chanmon_cfgs(2);
8670         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8671         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8672         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8673
8674         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).0.contents.short_channel_id;
8675
8676         {
8677                 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200).unwrap();
8678                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8679                 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
8680                 check_added_monitors!(nodes[0], 1);
8681                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8682                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8683                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8684                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8685         }
8686         // Note that after leaving the above scope we have no knowledge of any arguments or return
8687         // values from previous calls.
8688         expect_pending_htlcs_forwardable!(nodes[1]);
8689         let events = nodes[1].node.get_and_clear_pending_events();
8690         assert_eq!(events.len(), 1);
8691         match events[0] {
8692                 Event::PaymentReceived { ref purpose, .. } => {
8693                         match &purpose {
8694                                 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
8695                                         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8696                                 },
8697                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
8698                         }
8699                 },
8700                 _ => panic!("Unexpected event"),
8701         }
8702 }
8703
8704 #[test]
8705 #[allow(deprecated)]
8706 fn test_secret_timeout() {
8707         // Simple test of payment secret storage time outs. After
8708         // `create_inbound_payment(_for_hash)_legacy` is removed, this test will be removed as well.
8709         let chanmon_cfgs = create_chanmon_cfgs(2);
8710         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8711         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8712         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8713
8714         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).0.contents.short_channel_id;
8715
8716         let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment_legacy(Some(100_000), 2).unwrap();
8717
8718         // We should fail to register the same payment hash twice, at least until we've connected a
8719         // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
8720         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8721                 assert_eq!(err, "Duplicate payment hash");
8722         } else { panic!(); }
8723         let mut block = {
8724                 let node_1_blocks = nodes[1].blocks.lock().unwrap();
8725                 Block {
8726                         header: BlockHeader {
8727                                 version: 0x2000000,
8728                                 prev_blockhash: node_1_blocks.last().unwrap().0.block_hash(),
8729                                 merkle_root: TxMerkleNode::all_zeros(),
8730                                 time: node_1_blocks.len() as u32 + 7200, bits: 42, nonce: 42 },
8731                         txdata: vec![],
8732                 }
8733         };
8734         connect_block(&nodes[1], &block);
8735         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8736                 assert_eq!(err, "Duplicate payment hash");
8737         } else { panic!(); }
8738
8739         // If we then connect the second block, we should be able to register the same payment hash
8740         // again (this time getting a new payment secret).
8741         block.header.prev_blockhash = block.header.block_hash();
8742         block.header.time += 1;
8743         connect_block(&nodes[1], &block);
8744         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2).unwrap();
8745         assert_ne!(payment_secret_1, our_payment_secret);
8746
8747         {
8748                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8749                 nodes[0].node.send_payment(&route, payment_hash, &Some(our_payment_secret), PaymentId(payment_hash.0)).unwrap();
8750                 check_added_monitors!(nodes[0], 1);
8751                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8752                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8753                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8754                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8755         }
8756         // Note that after leaving the above scope we have no knowledge of any arguments or return
8757         // values from previous calls.
8758         expect_pending_htlcs_forwardable!(nodes[1]);
8759         let events = nodes[1].node.get_and_clear_pending_events();
8760         assert_eq!(events.len(), 1);
8761         match events[0] {
8762                 Event::PaymentReceived { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret }, .. } => {
8763                         assert!(payment_preimage.is_none());
8764                         assert_eq!(payment_secret, our_payment_secret);
8765                         // We don't actually have the payment preimage with which to claim this payment!
8766                 },
8767                 _ => panic!("Unexpected event"),
8768         }
8769 }
8770
8771 #[test]
8772 fn test_bad_secret_hash() {
8773         // Simple test of unregistered payment hash/invalid payment secret handling
8774         let chanmon_cfgs = create_chanmon_cfgs(2);
8775         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8776         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8777         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8778
8779         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).0.contents.short_channel_id;
8780
8781         let random_payment_hash = PaymentHash([42; 32]);
8782         let random_payment_secret = PaymentSecret([43; 32]);
8783         let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2).unwrap();
8784         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8785
8786         // All the below cases should end up being handled exactly identically, so we macro the
8787         // resulting events.
8788         macro_rules! handle_unknown_invalid_payment_data {
8789                 ($payment_hash: expr) => {
8790                         check_added_monitors!(nodes[0], 1);
8791                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8792                         let payment_event = SendEvent::from_event(events.pop().unwrap());
8793                         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8794                         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8795
8796                         // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8797                         // again to process the pending backwards-failure of the HTLC
8798                         expect_pending_htlcs_forwardable!(nodes[1]);
8799                         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment{ payment_hash: $payment_hash }]);
8800                         check_added_monitors!(nodes[1], 1);
8801
8802                         // We should fail the payment back
8803                         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8804                         match events.pop().unwrap() {
8805                                 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8806                                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8807                                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8808                                 },
8809                                 _ => panic!("Unexpected event"),
8810                         }
8811                 }
8812         }
8813
8814         let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8815         // Error data is the HTLC value (100,000) and current block height
8816         let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8817
8818         // Send a payment with the right payment hash but the wrong payment secret
8819         nodes[0].node.send_payment(&route, our_payment_hash, &Some(random_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
8820         handle_unknown_invalid_payment_data!(our_payment_hash);
8821         expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8822
8823         // Send a payment with a random payment hash, but the right payment secret
8824         nodes[0].node.send_payment(&route, random_payment_hash, &Some(our_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8825         handle_unknown_invalid_payment_data!(random_payment_hash);
8826         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8827
8828         // Send a payment with a random payment hash and random payment secret
8829         nodes[0].node.send_payment(&route, random_payment_hash, &Some(random_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8830         handle_unknown_invalid_payment_data!(random_payment_hash);
8831         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8832 }
8833
8834 #[test]
8835 fn test_update_err_monitor_lockdown() {
8836         // Our monitor will lock update of local commitment transaction if a broadcastion condition
8837         // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8838         // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateStatus
8839         // error.
8840         //
8841         // This scenario may happen in a watchtower setup, where watchtower process a block height
8842         // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8843         // commitment at same time.
8844
8845         let chanmon_cfgs = create_chanmon_cfgs(2);
8846         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8847         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8848         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8849
8850         // Create some initial channel
8851         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8852         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8853
8854         // Rebalance the network to generate htlc in the two directions
8855         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8856
8857         // Route a HTLC from node 0 to node 1 (but don't settle)
8858         let (preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
8859
8860         // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8861         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8862         let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8863         let persister = test_utils::TestPersister::new();
8864         let watchtower = {
8865                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8866                 let mut w = test_utils::TestVecWriter(Vec::new());
8867                 monitor.write(&mut w).unwrap();
8868                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8869                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8870                 assert!(new_monitor == *monitor);
8871                 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);
8872                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8873                 watchtower
8874         };
8875         let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8876         let block = Block { header, txdata: vec![] };
8877         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8878         // transaction lock time requirements here.
8879         chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 0));
8880         watchtower.chain_monitor.block_connected(&block, 200);
8881
8882         // Try to update ChannelMonitor
8883         nodes[1].node.claim_funds(preimage);
8884         check_added_monitors!(nodes[1], 1);
8885         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
8886
8887         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8888         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8889         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8890         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8891                 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8892                         assert_eq!(watchtower.chain_monitor.update_channel(outpoint, update.clone()), ChannelMonitorUpdateStatus::PermanentFailure);
8893                         assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, update), ChannelMonitorUpdateStatus::Completed);
8894                 } else { assert!(false); }
8895         } else { assert!(false); };
8896         // Our local monitor is in-sync and hasn't processed yet timeout
8897         check_added_monitors!(nodes[0], 1);
8898         let events = nodes[0].node.get_and_clear_pending_events();
8899         assert_eq!(events.len(), 1);
8900 }
8901
8902 #[test]
8903 fn test_concurrent_monitor_claim() {
8904         // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8905         // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8906         // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8907         // state N+1 confirms. Alice claims output from state N+1.
8908
8909         let chanmon_cfgs = create_chanmon_cfgs(2);
8910         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8911         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8912         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8913
8914         // Create some initial channel
8915         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8916         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8917
8918         // Rebalance the network to generate htlc in the two directions
8919         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8920
8921         // Route a HTLC from node 0 to node 1 (but don't settle)
8922         route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8923
8924         // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8925         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8926         let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8927         let persister = test_utils::TestPersister::new();
8928         let watchtower_alice = {
8929                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8930                 let mut w = test_utils::TestVecWriter(Vec::new());
8931                 monitor.write(&mut w).unwrap();
8932                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8933                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8934                 assert!(new_monitor == *monitor);
8935                 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);
8936                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8937                 watchtower
8938         };
8939         let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8940         let block = Block { header, txdata: vec![] };
8941         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8942         // transaction lock time requirements here.
8943         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));
8944         watchtower_alice.chain_monitor.block_connected(&block, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8945
8946         // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8947         {
8948                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8949                 assert_eq!(txn.len(), 2);
8950                 txn.clear();
8951         }
8952
8953         // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8954         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8955         let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8956         let persister = test_utils::TestPersister::new();
8957         let watchtower_bob = {
8958                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8959                 let mut w = test_utils::TestVecWriter(Vec::new());
8960                 monitor.write(&mut w).unwrap();
8961                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8962                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8963                 assert!(new_monitor == *monitor);
8964                 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);
8965                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8966                 watchtower
8967         };
8968         let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8969         watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8970
8971         // Route another payment to generate another update with still previous HTLC pending
8972         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8973         {
8974                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
8975         }
8976         check_added_monitors!(nodes[1], 1);
8977
8978         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8979         assert_eq!(updates.update_add_htlcs.len(), 1);
8980         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8981         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8982                 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8983                         // Watchtower Alice should already have seen the block and reject the update
8984                         assert_eq!(watchtower_alice.chain_monitor.update_channel(outpoint, update.clone()), ChannelMonitorUpdateStatus::PermanentFailure);
8985                         assert_eq!(watchtower_bob.chain_monitor.update_channel(outpoint, update.clone()), ChannelMonitorUpdateStatus::Completed);
8986                         assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, update), ChannelMonitorUpdateStatus::Completed);
8987                 } else { assert!(false); }
8988         } else { assert!(false); };
8989         // Our local monitor is in-sync and hasn't processed yet timeout
8990         check_added_monitors!(nodes[0], 1);
8991
8992         //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8993         let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8994         watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8995
8996         // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8997         let bob_state_y;
8998         {
8999                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
9000                 assert_eq!(txn.len(), 2);
9001                 bob_state_y = txn[0].clone();
9002                 txn.clear();
9003         };
9004
9005         // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
9006         let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
9007         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);
9008         {
9009                 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
9010                 assert_eq!(htlc_txn.len(), 1);
9011                 check_spends!(htlc_txn[0], bob_state_y);
9012         }
9013 }
9014
9015 #[test]
9016 fn test_pre_lockin_no_chan_closed_update() {
9017         // Test that if a peer closes a channel in response to a funding_created message we don't
9018         // generate a channel update (as the channel cannot appear on chain without a funding_signed
9019         // message).
9020         //
9021         // Doing so would imply a channel monitor update before the initial channel monitor
9022         // registration, violating our API guarantees.
9023         //
9024         // Previously, full_stack_target managed to hit this case by opening then closing a channel,
9025         // then opening a second channel with the same funding output as the first (which is not
9026         // rejected because the first channel does not exist in the ChannelManager) and closing it
9027         // before receiving funding_signed.
9028         let chanmon_cfgs = create_chanmon_cfgs(2);
9029         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9030         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9031         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9032
9033         // Create an initial channel
9034         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9035         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9036         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_chan_msg);
9037         let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9038         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_chan_msg);
9039
9040         // Move the first channel through the funding flow...
9041         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
9042
9043         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9044         check_added_monitors!(nodes[0], 0);
9045
9046         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9047         let channel_id = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
9048         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
9049         assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
9050         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "Hi".to_string() }, true);
9051 }
9052
9053 #[test]
9054 fn test_htlc_no_detection() {
9055         // This test is a mutation to underscore the detection logic bug we had
9056         // before #653. HTLC value routed is above the remaining balance, thus
9057         // inverting HTLC and `to_remote` output. HTLC will come second and
9058         // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
9059         // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
9060         // outputs order detection for correct spending children filtring.
9061
9062         let chanmon_cfgs = create_chanmon_cfgs(2);
9063         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9064         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9065         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9066
9067         // Create some initial channels
9068         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9069
9070         send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
9071         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
9072         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
9073         assert_eq!(local_txn[0].input.len(), 1);
9074         assert_eq!(local_txn[0].output.len(), 3);
9075         check_spends!(local_txn[0], chan_1.3);
9076
9077         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
9078         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
9079         connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] });
9080         // We deliberately connect the local tx twice as this should provoke a failure calling
9081         // this test before #653 fix.
9082         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);
9083         check_closed_broadcast!(nodes[0], true);
9084         check_added_monitors!(nodes[0], 1);
9085         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
9086         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1);
9087
9088         let htlc_timeout = {
9089                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
9090                 assert_eq!(node_txn[1].input.len(), 1);
9091                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9092                 check_spends!(node_txn[1], local_txn[0]);
9093                 node_txn[1].clone()
9094         };
9095
9096         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
9097         connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] });
9098         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
9099         expect_payment_failed!(nodes[0], our_payment_hash, false);
9100 }
9101
9102 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
9103         // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
9104         // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
9105         // Carol, Alice would be the upstream node, and Carol the downstream.)
9106         //
9107         // Steps of the test:
9108         // 1) Alice sends a HTLC to Carol through Bob.
9109         // 2) Carol doesn't settle the HTLC.
9110         // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
9111         // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
9112         // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
9113         //    but can't be claimed as Bob doesn't have yet knowledge of the preimage.
9114         // 5) Carol release the preimage to Bob off-chain.
9115         // 6) Bob claims the offered output on the broadcasted commitment.
9116         let chanmon_cfgs = create_chanmon_cfgs(3);
9117         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9118         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9119         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9120
9121         // Create some initial channels
9122         let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9123         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9124
9125         // Steps (1) and (2):
9126         // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
9127         let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
9128
9129         // Check that Alice's commitment transaction now contains an output for this HTLC.
9130         let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
9131         check_spends!(alice_txn[0], chan_ab.3);
9132         assert_eq!(alice_txn[0].output.len(), 2);
9133         check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
9134         assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9135         assert_eq!(alice_txn.len(), 2);
9136
9137         // Steps (3) and (4):
9138         // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
9139         // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
9140         let mut force_closing_node = 0; // Alice force-closes
9141         let mut counterparty_node = 1; // Bob if Alice force-closes
9142
9143         // Bob force-closes
9144         if !broadcast_alice {
9145                 force_closing_node = 1;
9146                 counterparty_node = 0;
9147         }
9148         nodes[force_closing_node].node.force_close_broadcasting_latest_txn(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id()).unwrap();
9149         check_closed_broadcast!(nodes[force_closing_node], true);
9150         check_added_monitors!(nodes[force_closing_node], 1);
9151         check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
9152         if go_onchain_before_fulfill {
9153                 let txn_to_broadcast = match broadcast_alice {
9154                         true => alice_txn.clone(),
9155                         false => get_local_commitment_txn!(nodes[1], chan_ab.2)
9156                 };
9157                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
9158                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
9159                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
9160                 if broadcast_alice {
9161                         check_closed_broadcast!(nodes[1], true);
9162                         check_added_monitors!(nodes[1], 1);
9163                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
9164                 }
9165                 assert_eq!(bob_txn.len(), 1);
9166                 check_spends!(bob_txn[0], chan_ab.3);
9167         }
9168
9169         // Step (5):
9170         // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
9171         // process of removing the HTLC from their commitment transactions.
9172         nodes[2].node.claim_funds(payment_preimage);
9173         check_added_monitors!(nodes[2], 1);
9174         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
9175
9176         let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
9177         assert!(carol_updates.update_add_htlcs.is_empty());
9178         assert!(carol_updates.update_fail_htlcs.is_empty());
9179         assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
9180         assert!(carol_updates.update_fee.is_none());
9181         assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
9182
9183         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
9184         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false, false);
9185         // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
9186         if !go_onchain_before_fulfill && broadcast_alice {
9187                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9188                 assert_eq!(events.len(), 1);
9189                 match events[0] {
9190                         MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
9191                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9192                         },
9193                         _ => panic!("Unexpected event"),
9194                 };
9195         }
9196         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
9197         // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
9198         // Carol<->Bob's updated commitment transaction info.
9199         check_added_monitors!(nodes[1], 2);
9200
9201         let events = nodes[1].node.get_and_clear_pending_msg_events();
9202         assert_eq!(events.len(), 2);
9203         let bob_revocation = match events[0] {
9204                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
9205                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
9206                         (*msg).clone()
9207                 },
9208                 _ => panic!("Unexpected event"),
9209         };
9210         let bob_updates = match events[1] {
9211                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
9212                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
9213                         (*updates).clone()
9214                 },
9215                 _ => panic!("Unexpected event"),
9216         };
9217
9218         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
9219         check_added_monitors!(nodes[2], 1);
9220         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
9221         check_added_monitors!(nodes[2], 1);
9222
9223         let events = nodes[2].node.get_and_clear_pending_msg_events();
9224         assert_eq!(events.len(), 1);
9225         let carol_revocation = match events[0] {
9226                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
9227                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
9228                         (*msg).clone()
9229                 },
9230                 _ => panic!("Unexpected event"),
9231         };
9232         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
9233         check_added_monitors!(nodes[1], 1);
9234
9235         // If this test requires the force-closed channel to not be on-chain until after the fulfill,
9236         // here's where we put said channel's commitment tx on-chain.
9237         let mut txn_to_broadcast = alice_txn.clone();
9238         if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
9239         if !go_onchain_before_fulfill {
9240                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
9241                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
9242                 // If Bob was the one to force-close, he will have already passed these checks earlier.
9243                 if broadcast_alice {
9244                         check_closed_broadcast!(nodes[1], true);
9245                         check_added_monitors!(nodes[1], 1);
9246                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
9247                 }
9248                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9249                 if broadcast_alice {
9250                         // In `connect_block()`, the ChainMonitor and ChannelManager are separately notified about a
9251                         // new block being connected. The ChannelManager being notified triggers a monitor update,
9252                         // which triggers broadcasting our commitment tx and an HTLC-claiming tx. The ChainMonitor
9253                         // being notified triggers the HTLC-claiming tx redundantly, resulting in 3 total txs being
9254                         // broadcasted.
9255                         assert_eq!(bob_txn.len(), 3);
9256                         check_spends!(bob_txn[1], chan_ab.3);
9257                 } else {
9258                         assert_eq!(bob_txn.len(), 2);
9259                         check_spends!(bob_txn[0], chan_ab.3);
9260                 }
9261         }
9262
9263         // Step (6):
9264         // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
9265         // broadcasted commitment transaction.
9266         {
9267                 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
9268                 if go_onchain_before_fulfill {
9269                         // Bob should now have an extra broadcasted tx, for the preimage-claiming transaction.
9270                         assert_eq!(bob_txn.len(), 2);
9271                 }
9272                 let script_weight = match broadcast_alice {
9273                         true => OFFERED_HTLC_SCRIPT_WEIGHT,
9274                         false => ACCEPTED_HTLC_SCRIPT_WEIGHT
9275                 };
9276                 // If Alice force-closed and Bob didn't receive her commitment transaction until after he
9277                 // received Carol's fulfill, he broadcasts the HTLC-output-claiming transaction first. Else if
9278                 // Bob force closed or if he found out about Alice's commitment tx before receiving Carol's
9279                 // fulfill, then he broadcasts the HTLC-output-claiming transaction second.
9280                 if broadcast_alice && !go_onchain_before_fulfill {
9281                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
9282                         assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
9283                 } else {
9284                         check_spends!(bob_txn[1], txn_to_broadcast[0]);
9285                         assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
9286                 }
9287         }
9288 }
9289
9290 #[test]
9291 fn test_onchain_htlc_settlement_after_close() {
9292         do_test_onchain_htlc_settlement_after_close(true, true);
9293         do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
9294         do_test_onchain_htlc_settlement_after_close(true, false);
9295         do_test_onchain_htlc_settlement_after_close(false, false);
9296 }
9297
9298 #[test]
9299 fn test_duplicate_chan_id() {
9300         // Test that if a given peer tries to open a channel with the same channel_id as one that is
9301         // already open we reject it and keep the old channel.
9302         //
9303         // Previously, full_stack_target managed to figure out that if you tried to open two channels
9304         // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
9305         // the existing channel when we detect the duplicate new channel, screwing up our monitor
9306         // updating logic for the existing channel.
9307         let chanmon_cfgs = create_chanmon_cfgs(2);
9308         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9309         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9310         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9311
9312         // Create an initial channel
9313         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9314         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9315         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_chan_msg);
9316         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()));
9317
9318         // Try to create a second channel with the same temporary_channel_id as the first and check
9319         // that it is rejected.
9320         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_chan_msg);
9321         {
9322                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9323                 assert_eq!(events.len(), 1);
9324                 match events[0] {
9325                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9326                                 // Technically, at this point, nodes[1] would be justified in thinking both the
9327                                 // first (valid) and second (invalid) channels are closed, given they both have
9328                                 // the same non-temporary channel_id. However, currently we do not, so we just
9329                                 // move forward with it.
9330                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9331                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9332                         },
9333                         _ => panic!("Unexpected event"),
9334                 }
9335         }
9336
9337         // Move the first channel through the funding flow...
9338         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
9339
9340         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9341         check_added_monitors!(nodes[0], 0);
9342
9343         let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9344         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
9345         {
9346                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
9347                 assert_eq!(added_monitors.len(), 1);
9348                 assert_eq!(added_monitors[0].0, funding_output);
9349                 added_monitors.clear();
9350         }
9351         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9352
9353         let funding_outpoint = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
9354         let channel_id = funding_outpoint.to_channel_id();
9355
9356         // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
9357         // temporary one).
9358
9359         // First try to open a second channel with a temporary channel id equal to the txid-based one.
9360         // Technically this is allowed by the spec, but we don't support it and there's little reason
9361         // to. Still, it shouldn't cause any other issues.
9362         open_chan_msg.temporary_channel_id = channel_id;
9363         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_chan_msg);
9364         {
9365                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9366                 assert_eq!(events.len(), 1);
9367                 match events[0] {
9368                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9369                                 // Technically, at this point, nodes[1] would be justified in thinking both
9370                                 // channels are closed, but currently we do not, so we just move forward with it.
9371                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9372                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9373                         },
9374                         _ => panic!("Unexpected event"),
9375                 }
9376         }
9377
9378         // Now try to create a second channel which has a duplicate funding output.
9379         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9380         let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9381         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_chan_2_msg);
9382         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()));
9383         create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
9384
9385         let funding_created = {
9386                 let mut a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
9387                 // Once we call `get_outbound_funding_created` the channel has a duplicate channel_id as
9388                 // another channel in the ChannelManager - an invalid state. Thus, we'd panic later when we
9389                 // try to create another channel. Instead, we drop the channel entirely here (leaving the
9390                 // channelmanager in a possibly nonsense state instead).
9391                 let mut as_chan = a_channel_lock.by_id.remove(&open_chan_2_msg.temporary_channel_id).unwrap();
9392                 let logger = test_utils::TestLogger::new();
9393                 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
9394         };
9395         check_added_monitors!(nodes[0], 0);
9396         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
9397         // At this point we'll try to add a duplicate channel monitor, which will be rejected, but
9398         // still needs to be cleared here.
9399         check_added_monitors!(nodes[1], 1);
9400
9401         // ...still, nodes[1] will reject the duplicate channel.
9402         {
9403                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9404                 assert_eq!(events.len(), 1);
9405                 match events[0] {
9406                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9407                                 // Technically, at this point, nodes[1] would be justified in thinking both
9408                                 // channels are closed, but currently we do not, so we just move forward with it.
9409                                 assert_eq!(msg.channel_id, channel_id);
9410                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9411                         },
9412                         _ => panic!("Unexpected event"),
9413                 }
9414         }
9415
9416         // finally, finish creating the original channel and send a payment over it to make sure
9417         // everything is functional.
9418         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
9419         {
9420                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9421                 assert_eq!(added_monitors.len(), 1);
9422                 assert_eq!(added_monitors[0].0, funding_output);
9423                 added_monitors.clear();
9424         }
9425
9426         let events_4 = nodes[0].node.get_and_clear_pending_events();
9427         assert_eq!(events_4.len(), 0);
9428         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9429         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9430
9431         let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9432         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9433         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9434         send_payment(&nodes[0], &[&nodes[1]], 8000000);
9435 }
9436
9437 #[test]
9438 fn test_error_chans_closed() {
9439         // Test that we properly handle error messages, closing appropriate channels.
9440         //
9441         // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
9442         // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
9443         // we can test various edge cases around it to ensure we don't regress.
9444         let chanmon_cfgs = create_chanmon_cfgs(3);
9445         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9446         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9447         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9448
9449         // Create some initial channels
9450         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9451         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9452         let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9453
9454         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9455         assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
9456         assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
9457
9458         // Closing a channel from a different peer has no effect
9459         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
9460         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9461
9462         // Closing one channel doesn't impact others
9463         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
9464         check_added_monitors!(nodes[0], 1);
9465         check_closed_broadcast!(nodes[0], false);
9466         check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
9467         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
9468         assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
9469         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);
9470         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);
9471
9472         // A null channel ID should close all channels
9473         let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9474         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
9475         check_added_monitors!(nodes[0], 2);
9476         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
9477         let events = nodes[0].node.get_and_clear_pending_msg_events();
9478         assert_eq!(events.len(), 2);
9479         match events[0] {
9480                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9481                         assert_eq!(msg.contents.flags & 2, 2);
9482                 },
9483                 _ => panic!("Unexpected event"),
9484         }
9485         match events[1] {
9486                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9487                         assert_eq!(msg.contents.flags & 2, 2);
9488                 },
9489                 _ => panic!("Unexpected event"),
9490         }
9491         // Note that at this point users of a standard PeerHandler will end up calling
9492         // peer_disconnected with no_connection_possible set to false, duplicating the
9493         // close-all-channels logic. That's OK, we don't want to end up not force-closing channels for
9494         // users with their own peer handling logic. We duplicate the call here, however.
9495         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9496         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9497
9498         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
9499         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9500         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9501 }
9502
9503 #[test]
9504 fn test_invalid_funding_tx() {
9505         // Test that we properly handle invalid funding transactions sent to us from a peer.
9506         //
9507         // Previously, all other major lightning implementations had failed to properly sanitize
9508         // funding transactions from their counterparties, leading to a multi-implementation critical
9509         // security vulnerability (though we always sanitized properly, we've previously had
9510         // un-released crashes in the sanitization process).
9511         //
9512         // Further, if the funding transaction is consensus-valid, confirms, and is later spent, we'd
9513         // previously have crashed in `ChannelMonitor` even though we closed the channel as bogus and
9514         // gave up on it. We test this here by generating such a transaction.
9515         let chanmon_cfgs = create_chanmon_cfgs(2);
9516         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9517         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9518         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9519
9520         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
9521         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()));
9522         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()));
9523
9524         let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
9525
9526         // Create a witness program which can be spent by a 4-empty-stack-elements witness and which is
9527         // 136 bytes long. This matches our "accepted HTLC preimage spend" matching, previously causing
9528         // a panic as we'd try to extract a 32 byte preimage from a witness element without checking
9529         // its length.
9530         let mut wit_program: Vec<u8> = channelmonitor::deliberately_bogus_accepted_htlc_witness_program();
9531         let wit_program_script: Script = wit_program.into();
9532         for output in tx.output.iter_mut() {
9533                 // Make the confirmed funding transaction have a bogus script_pubkey
9534                 output.script_pubkey = Script::new_v0_p2wsh(&wit_program_script.wscript_hash());
9535         }
9536
9537         nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
9538         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()));
9539         check_added_monitors!(nodes[1], 1);
9540
9541         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()));
9542         check_added_monitors!(nodes[0], 1);
9543
9544         let events_1 = nodes[0].node.get_and_clear_pending_events();
9545         assert_eq!(events_1.len(), 0);
9546
9547         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9548         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9549         nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9550
9551         let expected_err = "funding tx had wrong script/value or output index";
9552         confirm_transaction_at(&nodes[1], &tx, 1);
9553         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
9554         check_added_monitors!(nodes[1], 1);
9555         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9556         assert_eq!(events_2.len(), 1);
9557         if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9558                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9559                 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
9560                         assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
9561                 } else { panic!(); }
9562         } else { panic!(); }
9563         assert_eq!(nodes[1].node.list_channels().len(), 0);
9564
9565         // Now confirm a spend of the (bogus) funding transaction. As long as the witness is 5 elements
9566         // long the ChannelMonitor will try to read 32 bytes from the second-to-last element, panicing
9567         // as its not 32 bytes long.
9568         let mut spend_tx = Transaction {
9569                 version: 2i32, lock_time: PackedLockTime::ZERO,
9570                 input: tx.output.iter().enumerate().map(|(idx, _)| TxIn {
9571                         previous_output: BitcoinOutPoint {
9572                                 txid: tx.txid(),
9573                                 vout: idx as u32,
9574                         },
9575                         script_sig: Script::new(),
9576                         sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
9577                         witness: Witness::from_vec(channelmonitor::deliberately_bogus_accepted_htlc_witness())
9578                 }).collect(),
9579                 output: vec![TxOut {
9580                         value: 1000,
9581                         script_pubkey: Script::new(),
9582                 }]
9583         };
9584         check_spends!(spend_tx, tx);
9585         mine_transaction(&nodes[1], &spend_tx);
9586 }
9587
9588 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9589         // In the first version of the chain::Confirm interface, after a refactor was made to not
9590         // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9591         // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9592         // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9593         // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9594         // spending transaction until height N+1 (or greater). This was due to the way
9595         // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9596         // spending transaction at the height the input transaction was confirmed at, not whether we
9597         // should broadcast a spending transaction at the current height.
9598         // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9599         // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9600         // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9601         // until we learned about an additional block.
9602         //
9603         // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9604         // aren't broadcasting transactions too early (ie not broadcasting them at all).
9605         let chanmon_cfgs = create_chanmon_cfgs(3);
9606         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9607         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9608         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9609         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9610
9611         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9612         let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9613         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9614         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
9615         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9616
9617         nodes[1].node.force_close_broadcasting_latest_txn(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
9618         check_closed_broadcast!(nodes[1], true);
9619         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
9620         check_added_monitors!(nodes[1], 1);
9621         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9622         assert_eq!(node_txn.len(), 1);
9623
9624         let conf_height = nodes[1].best_block_info().1;
9625         if !test_height_before_timelock {
9626                 connect_blocks(&nodes[1], 24 * 6);
9627         }
9628         nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9629                 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9630         if test_height_before_timelock {
9631                 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9632                 // generate any events or broadcast any transactions
9633                 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9634                 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9635         } else {
9636                 // We should broadcast an HTLC transaction spending our funding transaction first
9637                 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9638                 assert_eq!(spending_txn.len(), 2);
9639                 assert_eq!(spending_txn[0], node_txn[0]);
9640                 check_spends!(spending_txn[1], node_txn[0]);
9641                 // We should also generate a SpendableOutputs event with the to_self output (as its
9642                 // timelock is up).
9643                 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9644                 assert_eq!(descriptor_spend_txn.len(), 1);
9645
9646                 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9647                 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9648                 // additional block built on top of the current chain.
9649                 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9650                         &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9651                 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 }]);
9652                 check_added_monitors!(nodes[1], 1);
9653
9654                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9655                 assert!(updates.update_add_htlcs.is_empty());
9656                 assert!(updates.update_fulfill_htlcs.is_empty());
9657                 assert_eq!(updates.update_fail_htlcs.len(), 1);
9658                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9659                 assert!(updates.update_fee.is_none());
9660                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9661                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9662                 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9663         }
9664 }
9665
9666 #[test]
9667 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9668         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9669         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9670 }
9671
9672 #[test]
9673 fn test_forwardable_regen() {
9674         // Tests that if we reload a ChannelManager while forwards are pending we will regenerate the
9675         // PendingHTLCsForwardable event automatically, ensuring we don't forget to forward/receive
9676         // HTLCs.
9677         // We test it for both payment receipt and payment forwarding.
9678
9679         let chanmon_cfgs = create_chanmon_cfgs(3);
9680         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9681         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9682         let persister: test_utils::TestPersister;
9683         let new_chain_monitor: test_utils::TestChainMonitor;
9684         let nodes_1_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
9685         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9686         let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
9687         let chan_id_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
9688
9689         // First send a payment to nodes[1]
9690         let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
9691         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
9692         check_added_monitors!(nodes[0], 1);
9693
9694         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9695         assert_eq!(events.len(), 1);
9696         let payment_event = SendEvent::from_event(events.pop().unwrap());
9697         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9698         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9699
9700         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9701
9702         // Next send a payment which is forwarded by nodes[1]
9703         let (route_2, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 200_000);
9704         nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
9705         check_added_monitors!(nodes[0], 1);
9706
9707         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9708         assert_eq!(events.len(), 1);
9709         let payment_event = SendEvent::from_event(events.pop().unwrap());
9710         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9711         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9712
9713         // There is already a PendingHTLCsForwardable event "pending" so another one will not be
9714         // generated
9715         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
9716
9717         // Now restart nodes[1] and make sure it regenerates a single PendingHTLCsForwardable
9718         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9719         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9720
9721         let nodes_1_serialized = nodes[1].node.encode();
9722         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9723         let mut chan_1_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9724         get_monitor!(nodes[1], chan_id_1).write(&mut chan_0_monitor_serialized).unwrap();
9725         get_monitor!(nodes[1], chan_id_2).write(&mut chan_1_monitor_serialized).unwrap();
9726
9727         persister = test_utils::TestPersister::new();
9728         let keys_manager = &chanmon_cfgs[1].keys_manager;
9729         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);
9730         nodes[1].chain_monitor = &new_chain_monitor;
9731
9732         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
9733         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9734                 &mut chan_0_monitor_read, keys_manager).unwrap();
9735         assert!(chan_0_monitor_read.is_empty());
9736         let mut chan_1_monitor_read = &chan_1_monitor_serialized.0[..];
9737         let (_, mut chan_1_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9738                 &mut chan_1_monitor_read, keys_manager).unwrap();
9739         assert!(chan_1_monitor_read.is_empty());
9740
9741         let mut nodes_1_read = &nodes_1_serialized[..];
9742         let (_, nodes_1_deserialized_tmp) = {
9743                 let mut channel_monitors = HashMap::new();
9744                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
9745                 channel_monitors.insert(chan_1_monitor.get_funding_txo().0, &mut chan_1_monitor);
9746                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_1_read, ChannelManagerReadArgs {
9747                         default_config: UserConfig::default(),
9748                         keys_manager,
9749                         fee_estimator: node_cfgs[1].fee_estimator,
9750                         chain_monitor: nodes[1].chain_monitor,
9751                         tx_broadcaster: nodes[1].tx_broadcaster.clone(),
9752                         logger: nodes[1].logger,
9753                         channel_monitors,
9754                 }).unwrap()
9755         };
9756         nodes_1_deserialized = nodes_1_deserialized_tmp;
9757         assert!(nodes_1_read.is_empty());
9758
9759         assert_eq!(nodes[1].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor),
9760                 ChannelMonitorUpdateStatus::Completed);
9761         assert_eq!(nodes[1].chain_monitor.watch_channel(chan_1_monitor.get_funding_txo().0, chan_1_monitor),
9762                 ChannelMonitorUpdateStatus::Completed);
9763         nodes[1].node = &nodes_1_deserialized;
9764         check_added_monitors!(nodes[1], 2);
9765
9766         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9767         // Note that nodes[1] and nodes[2] resend their channel_ready here since they haven't updated
9768         // the commitment state.
9769         reconnect_nodes(&nodes[1], &nodes[2], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9770
9771         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
9772
9773         expect_pending_htlcs_forwardable!(nodes[1]);
9774         expect_payment_received!(nodes[1], payment_hash, payment_secret, 100_000);
9775         check_added_monitors!(nodes[1], 1);
9776
9777         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9778         assert_eq!(events.len(), 1);
9779         let payment_event = SendEvent::from_event(events.pop().unwrap());
9780         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9781         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false);
9782         expect_pending_htlcs_forwardable!(nodes[2]);
9783         expect_payment_received!(nodes[2], payment_hash_2, payment_secret_2, 200_000);
9784
9785         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
9786         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage_2);
9787 }
9788
9789 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
9790         let chanmon_cfgs = create_chanmon_cfgs(2);
9791         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9792         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9793         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9794
9795         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9796
9797         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
9798                 .with_features(channelmanager::provided_invoice_features());
9799         let route = get_route!(nodes[0], payment_params, 10_000, TEST_FINAL_CLTV).unwrap();
9800
9801         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9802
9803         {
9804                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
9805                 check_added_monitors!(nodes[0], 1);
9806                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9807                 assert_eq!(events.len(), 1);
9808                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9809                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9810                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9811         }
9812         expect_pending_htlcs_forwardable!(nodes[1]);
9813         expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9814
9815         {
9816                 // Note that we use a different PaymentId here to allow us to duplicativly pay
9817                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_secret.0)).unwrap();
9818                 check_added_monitors!(nodes[0], 1);
9819                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9820                 assert_eq!(events.len(), 1);
9821                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9822                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9823                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9824                 // At this point, nodes[1] would notice it has too much value for the payment. It will
9825                 // assume the second is a privacy attack (no longer particularly relevant
9826                 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9827                 // the first HTLC delivered above.
9828         }
9829
9830         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9831         nodes[1].node.process_pending_htlc_forwards();
9832
9833         if test_for_second_fail_panic {
9834                 // Now we go fail back the first HTLC from the user end.
9835                 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9836
9837                 let expected_destinations = vec![
9838                         HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9839                         HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9840                 ];
9841                 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1],  expected_destinations);
9842                 nodes[1].node.process_pending_htlc_forwards();
9843
9844                 check_added_monitors!(nodes[1], 1);
9845                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9846                 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9847
9848                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9849                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9850                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9851
9852                 let failure_events = nodes[0].node.get_and_clear_pending_events();
9853                 assert_eq!(failure_events.len(), 2);
9854                 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9855                 if let Event::PaymentPathFailed { .. } = failure_events[1] {} else { panic!(); }
9856         } else {
9857                 // Let the second HTLC fail and claim the first
9858                 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9859                 nodes[1].node.process_pending_htlc_forwards();
9860
9861                 check_added_monitors!(nodes[1], 1);
9862                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9863                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9864                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9865
9866                 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9867
9868                 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9869         }
9870 }
9871
9872 #[test]
9873 fn test_dup_htlc_second_fail_panic() {
9874         // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9875         // value for the payment, we'd fail back both HTLCs after generating a `PaymentReceived` event.
9876         // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9877         // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9878         do_test_dup_htlc_second_rejected(true);
9879 }
9880
9881 #[test]
9882 fn test_dup_htlc_second_rejected() {
9883         // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9884         // simply reject the second HTLC but are still able to claim the first HTLC.
9885         do_test_dup_htlc_second_rejected(false);
9886 }
9887
9888 #[test]
9889 fn test_inconsistent_mpp_params() {
9890         // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9891         // such HTLC and allow the second to stay.
9892         let chanmon_cfgs = create_chanmon_cfgs(4);
9893         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9894         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9895         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9896
9897         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9898         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9899         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9900         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());
9901
9902         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id())
9903                 .with_features(channelmanager::provided_invoice_features());
9904         let mut route = get_route!(nodes[0], payment_params, 15_000_000, TEST_FINAL_CLTV).unwrap();
9905         assert_eq!(route.paths.len(), 2);
9906         route.paths.sort_by(|path_a, _| {
9907                 // Sort the path so that the path through nodes[1] comes first
9908                 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
9909                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9910         });
9911         let payment_params_opt = Some(payment_params);
9912
9913         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9914
9915         let cur_height = nodes[0].best_block_info().1;
9916         let payment_id = PaymentId([42; 32]);
9917
9918         let session_privs = {
9919                 // We create a fake route here so that we start with three pending HTLCs, which we'll
9920                 // ultimately have, just not right away.
9921                 let mut dup_route = route.clone();
9922                 dup_route.paths.push(route.paths[1].clone());
9923                 nodes[0].node.test_add_new_pending_payment(our_payment_hash, Some(our_payment_secret), payment_id, &dup_route).unwrap()
9924         };
9925         {
9926                 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();
9927                 check_added_monitors!(nodes[0], 1);
9928
9929                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9930                 assert_eq!(events.len(), 1);
9931                 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9932         }
9933         assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9934
9935         {
9936                 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();
9937                 check_added_monitors!(nodes[0], 1);
9938
9939                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9940                 assert_eq!(events.len(), 1);
9941                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9942
9943                 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9944                 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9945
9946                 expect_pending_htlcs_forwardable!(nodes[2]);
9947                 check_added_monitors!(nodes[2], 1);
9948
9949                 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9950                 assert_eq!(events.len(), 1);
9951                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9952
9953                 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9954                 check_added_monitors!(nodes[3], 0);
9955                 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9956
9957                 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9958                 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9959                 // post-payment_secrets) and fail back the new HTLC.
9960         }
9961         expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9962         nodes[3].node.process_pending_htlc_forwards();
9963         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9964         nodes[3].node.process_pending_htlc_forwards();
9965
9966         check_added_monitors!(nodes[3], 1);
9967
9968         let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9969         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9970         commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9971
9972         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 }]);
9973         check_added_monitors!(nodes[2], 1);
9974
9975         let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9976         nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9977         commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9978
9979         expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9980
9981         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();
9982         check_added_monitors!(nodes[0], 1);
9983
9984         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9985         assert_eq!(events.len(), 1);
9986         pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9987
9988         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9989 }
9990
9991 #[test]
9992 fn test_keysend_payments_to_public_node() {
9993         let chanmon_cfgs = create_chanmon_cfgs(2);
9994         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9995         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9996         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9997
9998         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9999         let network_graph = nodes[0].network_graph;
10000         let payer_pubkey = nodes[0].node.get_our_node_id();
10001         let payee_pubkey = nodes[1].node.get_our_node_id();
10002         let route_params = RouteParameters {
10003                 payment_params: PaymentParameters::for_keysend(payee_pubkey),
10004                 final_value_msat: 10000,
10005                 final_cltv_expiry_delta: 40,
10006         };
10007         let scorer = test_utils::TestScorer::with_penalty(0);
10008         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
10009         let route = find_route(&payer_pubkey, &route_params, &network_graph, None, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
10010
10011         let test_preimage = PaymentPreimage([42; 32]);
10012         let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage), PaymentId(test_preimage.0)).unwrap();
10013         check_added_monitors!(nodes[0], 1);
10014         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
10015         assert_eq!(events.len(), 1);
10016         let event = events.pop().unwrap();
10017         let path = vec![&nodes[1]];
10018         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
10019         claim_payment(&nodes[0], &path, test_preimage);
10020 }
10021
10022 #[test]
10023 fn test_keysend_payments_to_private_node() {
10024         let chanmon_cfgs = create_chanmon_cfgs(2);
10025         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10026         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10027         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10028
10029         let payer_pubkey = nodes[0].node.get_our_node_id();
10030         let payee_pubkey = nodes[1].node.get_our_node_id();
10031         nodes[0].node.peer_connected(&payee_pubkey, &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
10032         nodes[1].node.peer_connected(&payer_pubkey, &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
10033
10034         let _chan = create_chan_between_nodes(&nodes[0], &nodes[1], channelmanager::provided_init_features(), channelmanager::provided_init_features());
10035         let route_params = RouteParameters {
10036                 payment_params: PaymentParameters::for_keysend(payee_pubkey),
10037                 final_value_msat: 10000,
10038                 final_cltv_expiry_delta: 40,
10039         };
10040         let network_graph = nodes[0].network_graph;
10041         let first_hops = nodes[0].node.list_usable_channels();
10042         let scorer = test_utils::TestScorer::with_penalty(0);
10043         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
10044         let route = find_route(
10045                 &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
10046                 nodes[0].logger, &scorer, &random_seed_bytes
10047         ).unwrap();
10048
10049         let test_preimage = PaymentPreimage([42; 32]);
10050         let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage), PaymentId(test_preimage.0)).unwrap();
10051         check_added_monitors!(nodes[0], 1);
10052         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
10053         assert_eq!(events.len(), 1);
10054         let event = events.pop().unwrap();
10055         let path = vec![&nodes[1]];
10056         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
10057         claim_payment(&nodes[0], &path, test_preimage);
10058 }
10059
10060 #[test]
10061 fn test_double_partial_claim() {
10062         // Test what happens if a node receives a payment, generates a PaymentReceived event, the HTLCs
10063         // time out, the sender resends only some of the MPP parts, then the user processes the
10064         // PaymentReceived event, ensuring they don't inadvertently claim only part of the full payment
10065         // amount.
10066         let chanmon_cfgs = create_chanmon_cfgs(4);
10067         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
10068         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
10069         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
10070
10071         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
10072         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
10073         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
10074         create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
10075
10076         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
10077         assert_eq!(route.paths.len(), 2);
10078         route.paths.sort_by(|path_a, _| {
10079                 // Sort the path so that the path through nodes[1] comes first
10080                 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
10081                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
10082         });
10083
10084         send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 15_000_000, payment_hash, payment_secret);
10085         // nodes[3] has now received a PaymentReceived event...which it will take some (exorbitant)
10086         // amount of time to respond to.
10087
10088         // Connect some blocks to time out the payment
10089         connect_blocks(&nodes[3], TEST_FINAL_CLTV);
10090         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // To get the same height for sending later
10091
10092         let failed_destinations = vec![
10093                 HTLCDestination::FailedPayment { payment_hash },
10094                 HTLCDestination::FailedPayment { payment_hash },
10095         ];
10096         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations);
10097
10098         pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash);
10099
10100         // nodes[1] now retries one of the two paths...
10101         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
10102         check_added_monitors!(nodes[0], 2);
10103
10104         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
10105         assert_eq!(events.len(), 2);
10106         pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
10107
10108         // At this point nodes[3] has received one half of the payment, and the user goes to handle
10109         // that PaymentReceived event they got hours ago and never handled...we should refuse to claim.
10110         nodes[3].node.claim_funds(payment_preimage);
10111         check_added_monitors!(nodes[3], 0);
10112         assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
10113 }
10114
10115 fn do_test_partial_claim_before_restart(persist_both_monitors: bool) {
10116         // Test what happens if a node receives an MPP payment, claims it, but crashes before
10117         // persisting the ChannelManager. If `persist_both_monitors` is false, also crash after only
10118         // updating one of the two channels' ChannelMonitors. As a result, on startup, we'll (a) still
10119         // have the PaymentReceived event, (b) have one (or two) channel(s) that goes on chain with the
10120         // HTLC preimage in them, and (c) optionally have one channel that is live off-chain but does
10121         // not have the preimage tied to the still-pending HTLC.
10122         //
10123         // To get to the correct state, on startup we should propagate the preimage to the
10124         // still-off-chain channel, claiming the HTLC as soon as the peer connects, with the monitor
10125         // receiving the preimage without a state update.
10126         //
10127         // Further, we should generate a `PaymentClaimed` event to inform the user that the payment was
10128         // definitely claimed.
10129         let chanmon_cfgs = create_chanmon_cfgs(4);
10130         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
10131         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
10132
10133         let persister: test_utils::TestPersister;
10134         let new_chain_monitor: test_utils::TestChainMonitor;
10135         let nodes_3_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
10136
10137         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
10138
10139         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
10140         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
10141         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;
10142         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;
10143
10144         // Create an MPP route for 15k sats, more than the default htlc-max of 10%
10145         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
10146         assert_eq!(route.paths.len(), 2);
10147         route.paths.sort_by(|path_a, _| {
10148                 // Sort the path so that the path through nodes[1] comes first
10149                 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
10150                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
10151         });
10152
10153         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
10154         check_added_monitors!(nodes[0], 2);
10155
10156         // Send the payment through to nodes[3] *without* clearing the PaymentReceived event
10157         let mut send_events = nodes[0].node.get_and_clear_pending_msg_events();
10158         assert_eq!(send_events.len(), 2);
10159         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);
10160         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);
10161
10162         // Now that we have an MPP payment pending, get the latest encoded copies of nodes[3]'s
10163         // monitors and ChannelManager, for use later, if we don't want to persist both monitors.
10164         let mut original_monitor = test_utils::TestVecWriter(Vec::new());
10165         if !persist_both_monitors {
10166                 for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
10167                         if outpoint.to_channel_id() == chan_id_not_persisted {
10168                                 assert!(original_monitor.0.is_empty());
10169                                 nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut original_monitor).unwrap();
10170                         }
10171                 }
10172         }
10173
10174         let mut original_manager = test_utils::TestVecWriter(Vec::new());
10175         nodes[3].node.write(&mut original_manager).unwrap();
10176
10177         expect_payment_received!(nodes[3], payment_hash, payment_secret, 15_000_000);
10178
10179         nodes[3].node.claim_funds(payment_preimage);
10180         check_added_monitors!(nodes[3], 2);
10181         expect_payment_claimed!(nodes[3], payment_hash, 15_000_000);
10182
10183         // Now fetch one of the two updated ChannelMonitors from nodes[3], and restart pretending we
10184         // crashed in between the two persistence calls - using one old ChannelMonitor and one new one,
10185         // with the old ChannelManager.
10186         let mut updated_monitor = test_utils::TestVecWriter(Vec::new());
10187         for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
10188                 if outpoint.to_channel_id() == chan_id_persisted {
10189                         assert!(updated_monitor.0.is_empty());
10190                         nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut updated_monitor).unwrap();
10191                 }
10192         }
10193         // If `persist_both_monitors` is set, get the second monitor here as well
10194         if persist_both_monitors {
10195                 for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
10196                         if outpoint.to_channel_id() == chan_id_not_persisted {
10197                                 assert!(original_monitor.0.is_empty());
10198                                 nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut original_monitor).unwrap();
10199                         }
10200                 }
10201         }
10202
10203         // Now restart nodes[3].
10204         persister = test_utils::TestPersister::new();
10205         let keys_manager = &chanmon_cfgs[3].keys_manager;
10206         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);
10207         nodes[3].chain_monitor = &new_chain_monitor;
10208         let mut monitors = Vec::new();
10209         for mut monitor_data in [original_monitor, updated_monitor].iter() {
10210                 let (_, mut deserialized_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut &monitor_data.0[..], keys_manager).unwrap();
10211                 monitors.push(deserialized_monitor);
10212         }
10213
10214         let config = UserConfig::default();
10215         nodes_3_deserialized = {
10216                 let mut channel_monitors = HashMap::new();
10217                 for monitor in monitors.iter_mut() {
10218                         channel_monitors.insert(monitor.get_funding_txo().0, monitor);
10219                 }
10220                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut &original_manager.0[..], ChannelManagerReadArgs {
10221                         default_config: config,
10222                         keys_manager,
10223                         fee_estimator: node_cfgs[3].fee_estimator,
10224                         chain_monitor: nodes[3].chain_monitor,
10225                         tx_broadcaster: nodes[3].tx_broadcaster.clone(),
10226                         logger: nodes[3].logger,
10227                         channel_monitors,
10228                 }).unwrap().1
10229         };
10230         nodes[3].node = &nodes_3_deserialized;
10231
10232         for monitor in monitors {
10233                 // On startup the preimage should have been copied into the non-persisted monitor:
10234                 assert!(monitor.get_stored_preimages().contains_key(&payment_hash));
10235                 assert_eq!(nodes[3].chain_monitor.watch_channel(monitor.get_funding_txo().0.clone(), monitor),
10236                         ChannelMonitorUpdateStatus::Completed);
10237         }
10238         check_added_monitors!(nodes[3], 2);
10239
10240         nodes[1].node.peer_disconnected(&nodes[3].node.get_our_node_id(), false);
10241         nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), false);
10242
10243         // During deserialization, we should have closed one channel and broadcast its latest
10244         // commitment transaction. We should also still have the original PaymentReceived event we
10245         // never finished processing.
10246         let events = nodes[3].node.get_and_clear_pending_events();
10247         assert_eq!(events.len(), if persist_both_monitors { 4 } else { 3 });
10248         if let Event::PaymentReceived { amount_msat: 15_000_000, .. } = events[0] { } else { panic!(); }
10249         if let Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } = events[1] { } else { panic!(); }
10250         if persist_both_monitors {
10251                 if let Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } = events[2] { } else { panic!(); }
10252         }
10253
10254         // On restart, we should also get a duplicate PaymentClaimed event as we persisted the
10255         // ChannelManager prior to handling the original one.
10256         if let Event::PaymentClaimed { payment_hash: our_payment_hash, amount_msat: 15_000_000, .. } =
10257                 events[if persist_both_monitors { 3 } else { 2 }]
10258         {
10259                 assert_eq!(payment_hash, our_payment_hash);
10260         } else { panic!(); }
10261
10262         assert_eq!(nodes[3].node.list_channels().len(), if persist_both_monitors { 0 } else { 1 });
10263         if !persist_both_monitors {
10264                 // If one of the two channels is still live, reveal the payment preimage over it.
10265
10266                 nodes[3].node.peer_connected(&nodes[2].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
10267                 let reestablish_1 = get_chan_reestablish_msgs!(nodes[3], nodes[2]);
10268                 nodes[2].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
10269                 let reestablish_2 = get_chan_reestablish_msgs!(nodes[2], nodes[3]);
10270
10271                 nodes[2].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish_1[0]);
10272                 get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, nodes[3].node.get_our_node_id());
10273                 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
10274
10275                 nodes[3].node.handle_channel_reestablish(&nodes[2].node.get_our_node_id(), &reestablish_2[0]);
10276
10277                 // Once we call `get_and_clear_pending_msg_events` the holding cell is cleared and the HTLC
10278                 // claim should fly.
10279                 let ds_msgs = nodes[3].node.get_and_clear_pending_msg_events();
10280                 check_added_monitors!(nodes[3], 1);
10281                 assert_eq!(ds_msgs.len(), 2);
10282                 if let MessageSendEvent::SendChannelUpdate { .. } = ds_msgs[1] {} else { panic!(); }
10283
10284                 let cs_updates = match ds_msgs[0] {
10285                         MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
10286                                 nodes[2].node.handle_update_fulfill_htlc(&nodes[3].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
10287                                 check_added_monitors!(nodes[2], 1);
10288                                 let cs_updates = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
10289                                 expect_payment_forwarded!(nodes[2], nodes[0], nodes[3], Some(1000), false, false);
10290                                 commitment_signed_dance!(nodes[2], nodes[3], updates.commitment_signed, false, true);
10291                                 cs_updates
10292                         }
10293                         _ => panic!(),
10294                 };
10295
10296                 nodes[0].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &cs_updates.update_fulfill_htlcs[0]);
10297                 commitment_signed_dance!(nodes[0], nodes[2], cs_updates.commitment_signed, false, true);
10298                 expect_payment_sent!(nodes[0], payment_preimage);
10299         }
10300 }
10301
10302 #[test]
10303 fn test_partial_claim_before_restart() {
10304         do_test_partial_claim_before_restart(false);
10305         do_test_partial_claim_before_restart(true);
10306 }
10307
10308 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
10309 #[derive(Clone, Copy, PartialEq)]
10310 enum ExposureEvent {
10311         /// Breach occurs at HTLC forwarding (see `send_htlc`)
10312         AtHTLCForward,
10313         /// Breach occurs at HTLC reception (see `update_add_htlc`)
10314         AtHTLCReception,
10315         /// Breach occurs at outbound update_fee (see `send_update_fee`)
10316         AtUpdateFeeOutbound,
10317 }
10318
10319 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool) {
10320         // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
10321         // policy.
10322         //
10323         // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
10324         // trimmed-to-dust HTLC outbound balance and this new payment as included on next
10325         // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
10326         // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
10327         // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
10328         // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
10329         // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
10330         // might be available again for HTLC processing once the dust bandwidth has cleared up.
10331
10332         let chanmon_cfgs = create_chanmon_cfgs(2);
10333         let mut config = test_default_channel_config();
10334         config.channel_config.max_dust_htlc_exposure_msat = 5_000_000; // default setting value
10335         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10336         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
10337         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10338
10339         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
10340         let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10341         open_channel.max_htlc_value_in_flight_msat = 50_000_000;
10342         open_channel.max_accepted_htlcs = 60;
10343         if on_holder_tx {
10344                 open_channel.dust_limit_satoshis = 546;
10345         }
10346         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_channel);
10347         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10348         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_channel);
10349
10350         let opt_anchors = false;
10351
10352         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
10353
10354         if on_holder_tx {
10355                 if let Some(mut chan) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&temporary_channel_id) {
10356                         chan.holder_dust_limit_satoshis = 546;
10357                 }
10358         }
10359
10360         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
10361         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()));
10362         check_added_monitors!(nodes[1], 1);
10363
10364         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()));
10365         check_added_monitors!(nodes[0], 1);
10366
10367         let (channel_ready, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
10368         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
10369         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
10370
10371         let dust_buffer_feerate = {
10372                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
10373                 let chan = chan_lock.by_id.get(&channel_id).unwrap();
10374                 chan.get_dust_buffer_feerate(None) as u64
10375         };
10376         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;
10377         let dust_outbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
10378
10379         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;
10380         let dust_inbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
10381
10382         let dust_htlc_on_counterparty_tx: u64 = 25;
10383         let dust_htlc_on_counterparty_tx_msat: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
10384
10385         if on_holder_tx {
10386                 if dust_outbound_balance {
10387                         // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
10388                         // Outbound dust balance: 4372 sats
10389                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
10390                         for i in 0..dust_outbound_htlc_on_holder_tx {
10391                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
10392                                 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); }
10393                         }
10394                 } else {
10395                         // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
10396                         // Inbound dust balance: 4372 sats
10397                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
10398                         for _ in 0..dust_inbound_htlc_on_holder_tx {
10399                                 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
10400                         }
10401                 }
10402         } else {
10403                 if dust_outbound_balance {
10404                         // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
10405                         // Outbound dust balance: 5000 sats
10406                         for i in 0..dust_htlc_on_counterparty_tx {
10407                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
10408                                 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); }
10409                         }
10410                 } else {
10411                         // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
10412                         // Inbound dust balance: 5000 sats
10413                         for _ in 0..dust_htlc_on_counterparty_tx {
10414                                 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
10415                         }
10416                 }
10417         }
10418
10419         let dust_overflow = dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx + 1);
10420         if exposure_breach_event == ExposureEvent::AtHTLCForward {
10421                 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 });
10422                 let mut config = UserConfig::default();
10423                 // With default dust exposure: 5000 sats
10424                 if on_holder_tx {
10425                         let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * (dust_outbound_htlc_on_holder_tx + 1);
10426                         let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * dust_inbound_htlc_on_holder_tx + dust_outbound_htlc_on_holder_tx_msat;
10427                         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)));
10428                 } else {
10429                         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)));
10430                 }
10431         } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
10432                 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 });
10433                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
10434                 check_added_monitors!(nodes[1], 1);
10435                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
10436                 assert_eq!(events.len(), 1);
10437                 let payment_event = SendEvent::from_event(events.remove(0));
10438                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
10439                 // With default dust exposure: 5000 sats
10440                 if on_holder_tx {
10441                         // Outbound dust balance: 6399 sats
10442                         let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
10443                         let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
10444                         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);
10445                 } else {
10446                         // Outbound dust balance: 5200 sats
10447                         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);
10448                 }
10449         } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
10450                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 2_500_000);
10451                 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", ); }
10452                 {
10453                         let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
10454                         *feerate_lock = *feerate_lock * 10;
10455                 }
10456                 nodes[0].node.timer_tick_occurred();
10457                 check_added_monitors!(nodes[0], 1);
10458                 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);
10459         }
10460
10461         let _ = nodes[0].node.get_and_clear_pending_msg_events();
10462         let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
10463         added_monitors.clear();
10464 }
10465
10466 #[test]
10467 fn test_max_dust_htlc_exposure() {
10468         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true);
10469         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true);
10470         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true);
10471         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false);
10472         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false);
10473         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false);
10474         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true);
10475         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false);
10476         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true);
10477         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false);
10478         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false);
10479         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true);
10480 }
10481
10482 #[test]
10483 fn test_non_final_funding_tx() {
10484         let chanmon_cfgs = create_chanmon_cfgs(2);
10485         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10486         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10487         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10488
10489         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
10490         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10491         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_channel_message);
10492         let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10493         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_channel_message);
10494
10495         let best_height = nodes[0].node.best_block.read().unwrap().height();
10496
10497         let chan_id = *nodes[0].network_chan_count.borrow();
10498         let events = nodes[0].node.get_and_clear_pending_events();
10499         let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::Script::new(), sequence: Sequence(1), witness: Witness::from_vec(vec!(vec!(1))) };
10500         assert_eq!(events.len(), 1);
10501         let mut tx = match events[0] {
10502                 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
10503                         // Timelock the transaction _beyond_ the best client height + 2.
10504                         Transaction { version: chan_id as i32, lock_time: PackedLockTime(best_height + 3), input: vec![input], output: vec![TxOut {
10505                                 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
10506                         }]}
10507                 },
10508                 _ => panic!("Unexpected event"),
10509         };
10510         // Transaction should fail as it's evaluated as non-final for propagation.
10511         match nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()) {
10512                 Err(APIError::APIMisuseError { err }) => {
10513                         assert_eq!(format!("Funding transaction absolute timelock is non-final"), err);
10514                 },
10515                 _ => panic!()
10516         }
10517
10518         // However, transaction should be accepted if it's in a +2 headroom from best block.
10519         tx.lock_time = PackedLockTime(tx.lock_time.0 - 1);
10520         assert!(nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
10521         get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
10522 }