Make tests more robust against different connection styles
[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 chain;
15 use chain::{Confirm, Listen, Watch};
16 use chain::channelmonitor;
17 use chain::channelmonitor::{ChannelMonitor, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY};
18 use chain::transaction::OutPoint;
19 use chain::keysinterface::{BaseSign, KeysInterface};
20 use ln::{PaymentPreimage, PaymentSecret, PaymentHash};
21 use 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};
22 use ln::channelmanager::{ChannelManager, ChannelManagerReadArgs, PaymentId, RAACommitmentOrder, PaymentSendFailure, BREAKDOWN_TIMEOUT, MIN_CLTV_EXPIRY_DELTA, PAYMENT_EXPIRY_BLOCKS };
23 use ln::channel::{Channel, ChannelError};
24 use ln::{chan_utils, onion_utils};
25 use ln::chan_utils::{htlc_success_tx_weight, htlc_timeout_tx_weight, HTLCOutputInCommitment};
26 use routing::router::{PaymentParameters, Route, RouteHop, RouteParameters, find_route, get_route};
27 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
28 use ln::msgs;
29 use ln::msgs::{ChannelMessageHandler, RoutingMessageHandler, OptionalField, ErrorAction};
30 use util::enforcing_trait_impls::EnforcingSigner;
31 use util::{byte_utils, test_utils};
32 use util::events::{Event, MessageSendEvent, MessageSendEventsProvider, PaymentPurpose, ClosureReason};
33 use util::errors::APIError;
34 use util::ser::{Writeable, ReadableArgs};
35 use util::config::UserConfig;
36
37 use bitcoin::hash_types::BlockHash;
38 use bitcoin::blockdata::block::{Block, BlockHeader};
39 use bitcoin::blockdata::script::Builder;
40 use bitcoin::blockdata::opcodes;
41 use bitcoin::blockdata::constants::genesis_block;
42 use bitcoin::network::constants::Network;
43
44 use bitcoin::secp256k1::Secp256k1;
45 use bitcoin::secp256k1::{PublicKey,SecretKey};
46
47 use regex;
48
49 use io;
50 use prelude::*;
51 use alloc::collections::BTreeSet;
52 use core::default::Default;
53 use sync::{Arc, Mutex};
54
55 use ln::functional_test_utils::*;
56 use ln::chan_utils::CommitmentTransaction;
57
58 #[test]
59 fn test_insane_channel_opens() {
60         // Stand up a network of 2 nodes
61         use ln::channel::TOTAL_BITCOIN_SUPPLY_SATOSHIS;
62         let mut cfg = UserConfig::default();
63         cfg.peer_channel_config_limits.max_funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1;
64         let chanmon_cfgs = create_chanmon_cfgs(2);
65         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
66         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(cfg)]);
67         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
68
69         // Instantiate channel parameters where we push the maximum msats given our
70         // funding satoshis
71         let channel_value_sat = 31337; // same as funding satoshis
72         let channel_reserve_satoshis = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value_sat);
73         let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
74
75         // Have node0 initiate a channel to node1 with aforementioned parameters
76         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
77
78         // Extract the channel open message from node0 to node1
79         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
80
81         // Test helper that asserts we get the correct error string given a mutator
82         // that supposedly makes the channel open message insane
83         let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
84                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &message_mutator(open_channel_message.clone()));
85                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
86                 assert_eq!(msg_events.len(), 1);
87                 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
88                 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
89                         match action {
90                                 &ErrorAction::SendErrorMessage { .. } => {
91                                         nodes[1].logger.assert_log_regex("lightning::ln::channelmanager".to_string(), expected_regex, 1);
92                                 },
93                                 _ => panic!("unexpected event!"),
94                         }
95                 } else { assert!(false); }
96         };
97
98         use ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
99
100         // Test all mutations that would make the channel open message insane
101         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 });
102         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 });
103
104         insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
105
106         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 });
107
108         insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
109
110         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 });
111
112         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 });
113
114         insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
115
116         insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
117 }
118
119 #[test]
120 fn test_funding_exceeds_no_wumbo_limit() {
121         // Test that if a peer does not support wumbo channels, we'll refuse to open a wumbo channel to
122         // them.
123         use ln::channel::MAX_FUNDING_SATOSHIS_NO_WUMBO;
124         let chanmon_cfgs = create_chanmon_cfgs(2);
125         let mut node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
126         node_cfgs[1].features = InitFeatures::known().clear_wumbo();
127         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
128         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
129
130         match nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), MAX_FUNDING_SATOSHIS_NO_WUMBO + 1, 0, 42, None) {
131                 Err(APIError::APIMisuseError { err }) => {
132                         assert_eq!(format!("funding_value must not exceed {}, it was {}", MAX_FUNDING_SATOSHIS_NO_WUMBO, MAX_FUNDING_SATOSHIS_NO_WUMBO + 1), err);
133                 },
134                 _ => panic!()
135         }
136 }
137
138 fn do_test_counterparty_no_reserve(send_from_initiator: bool) {
139         // A peer providing a channel_reserve_satoshis of 0 (or less than our dust limit) is insecure,
140         // but only for them. Because some LSPs do it with some level of trust of the clients (for a
141         // substantial UX improvement), we explicitly allow it. Because it's unlikely to happen often
142         // in normal testing, we test it explicitly here.
143         let chanmon_cfgs = create_chanmon_cfgs(2);
144         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
145         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
146         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
147
148         // Have node0 initiate a channel to node1 with aforementioned parameters
149         let mut push_amt = 100_000_000;
150         let feerate_per_kw = 253;
151         let opt_anchors = false;
152         push_amt -= feerate_per_kw as u64 * (commitment_tx_base_weight(opt_anchors) + 4 * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000 * 1000;
153         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
154
155         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();
156         let mut open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
157         if !send_from_initiator {
158                 open_channel_message.channel_reserve_satoshis = 0;
159                 open_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
160         }
161         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel_message);
162
163         // Extract the channel accept message from node1 to node0
164         let mut accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
165         if send_from_initiator {
166                 accept_channel_message.channel_reserve_satoshis = 0;
167                 accept_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
168         }
169         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel_message);
170         {
171                 let mut lock;
172                 let mut chan = get_channel_ref!(if send_from_initiator { &nodes[1] } else { &nodes[0] }, lock, temp_channel_id);
173                 chan.holder_selected_channel_reserve_satoshis = 0;
174                 chan.holder_max_htlc_value_in_flight_msat = 100_000_000;
175         }
176
177         let funding_tx = sign_funding_transaction(&nodes[0], &nodes[1], 100_000, temp_channel_id);
178         let funding_msgs = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &funding_tx);
179         create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_msgs.0);
180
181         // nodes[0] should now be able to send the full balance to nodes[1], violating nodes[1]'s
182         // security model if it ever tries to send funds back to nodes[0] (but that's not our problem).
183         if send_from_initiator {
184                 send_payment(&nodes[0], &[&nodes[1]], 100_000_000
185                         // Note that for outbound channels we have to consider the commitment tx fee and the
186                         // "fee spike buffer", which is currently a multiple of the total commitment tx fee as
187                         // well as an additional HTLC.
188                         - FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE * commit_tx_fee_msat(feerate_per_kw, 2, opt_anchors));
189         } else {
190                 send_payment(&nodes[1], &[&nodes[0]], push_amt);
191         }
192 }
193
194 #[test]
195 fn test_counterparty_no_reserve() {
196         do_test_counterparty_no_reserve(true);
197         do_test_counterparty_no_reserve(false);
198 }
199
200 #[test]
201 fn test_async_inbound_update_fee() {
202         let chanmon_cfgs = create_chanmon_cfgs(2);
203         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
204         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
205         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
206         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
207
208         // balancing
209         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
210
211         // A                                        B
212         // update_fee                            ->
213         // send (1) commitment_signed            -.
214         //                                       <- update_add_htlc/commitment_signed
215         // send (2) RAA (awaiting remote revoke) -.
216         // (1) commitment_signed is delivered    ->
217         //                                       .- send (3) RAA (awaiting remote revoke)
218         // (2) RAA is delivered                  ->
219         //                                       .- send (4) commitment_signed
220         //                                       <- (3) RAA is delivered
221         // send (5) commitment_signed            -.
222         //                                       <- (4) commitment_signed is delivered
223         // send (6) RAA                          -.
224         // (5) commitment_signed is delivered    ->
225         //                                       <- RAA
226         // (6) RAA is delivered                  ->
227
228         // First nodes[0] generates an update_fee
229         {
230                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
231                 *feerate_lock += 20;
232         }
233         nodes[0].node.timer_tick_occurred();
234         check_added_monitors!(nodes[0], 1);
235
236         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
237         assert_eq!(events_0.len(), 1);
238         let (update_msg, commitment_signed) = match events_0[0] { // (1)
239                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
240                         (update_fee.as_ref(), commitment_signed)
241                 },
242                 _ => panic!("Unexpected event"),
243         };
244
245         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
246
247         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
248         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
249         nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
250         check_added_monitors!(nodes[1], 1);
251
252         let payment_event = {
253                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
254                 assert_eq!(events_1.len(), 1);
255                 SendEvent::from_event(events_1.remove(0))
256         };
257         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
258         assert_eq!(payment_event.msgs.len(), 1);
259
260         // ...now when the messages get delivered everyone should be happy
261         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
262         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
263         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
264         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
265         check_added_monitors!(nodes[0], 1);
266
267         // deliver(1), generate (3):
268         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
269         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
270         // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
271         check_added_monitors!(nodes[1], 1);
272
273         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
274         let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
275         assert!(bs_update.update_add_htlcs.is_empty()); // (4)
276         assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
277         assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
278         assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
279         assert!(bs_update.update_fee.is_none()); // (4)
280         check_added_monitors!(nodes[1], 1);
281
282         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
283         let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
284         assert!(as_update.update_add_htlcs.is_empty()); // (5)
285         assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
286         assert!(as_update.update_fail_htlcs.is_empty()); // (5)
287         assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
288         assert!(as_update.update_fee.is_none()); // (5)
289         check_added_monitors!(nodes[0], 1);
290
291         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
292         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
293         // only (6) so get_event_msg's assert(len == 1) passes
294         check_added_monitors!(nodes[0], 1);
295
296         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
297         let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
298         check_added_monitors!(nodes[1], 1);
299
300         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
301         check_added_monitors!(nodes[0], 1);
302
303         let events_2 = nodes[0].node.get_and_clear_pending_events();
304         assert_eq!(events_2.len(), 1);
305         match events_2[0] {
306                 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
307                 _ => panic!("Unexpected event"),
308         }
309
310         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
311         check_added_monitors!(nodes[1], 1);
312 }
313
314 #[test]
315 fn test_update_fee_unordered_raa() {
316         // Just the intro to the previous test followed by an out-of-order RAA (which caused a
317         // crash in an earlier version of the update_fee patch)
318         let chanmon_cfgs = create_chanmon_cfgs(2);
319         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
320         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
321         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
322         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
323
324         // balancing
325         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
326
327         // First nodes[0] generates an update_fee
328         {
329                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
330                 *feerate_lock += 20;
331         }
332         nodes[0].node.timer_tick_occurred();
333         check_added_monitors!(nodes[0], 1);
334
335         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
336         assert_eq!(events_0.len(), 1);
337         let update_msg = match events_0[0] { // (1)
338                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
339                         update_fee.as_ref()
340                 },
341                 _ => panic!("Unexpected event"),
342         };
343
344         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
345
346         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
347         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
348         nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
349         check_added_monitors!(nodes[1], 1);
350
351         let payment_event = {
352                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
353                 assert_eq!(events_1.len(), 1);
354                 SendEvent::from_event(events_1.remove(0))
355         };
356         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
357         assert_eq!(payment_event.msgs.len(), 1);
358
359         // ...now when the messages get delivered everyone should be happy
360         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
361         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
362         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
363         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
364         check_added_monitors!(nodes[0], 1);
365
366         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
367         check_added_monitors!(nodes[1], 1);
368
369         // We can't continue, sadly, because our (1) now has a bogus signature
370 }
371
372 #[test]
373 fn test_multi_flight_update_fee() {
374         let chanmon_cfgs = create_chanmon_cfgs(2);
375         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
376         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
377         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
378         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
379
380         // A                                        B
381         // update_fee/commitment_signed          ->
382         //                                       .- send (1) RAA and (2) commitment_signed
383         // update_fee (never committed)          ->
384         // (3) update_fee                        ->
385         // We have to manually generate the above update_fee, it is allowed by the protocol but we
386         // don't track which updates correspond to which revoke_and_ack responses so we're in
387         // AwaitingRAA mode and will not generate the update_fee yet.
388         //                                       <- (1) RAA delivered
389         // (3) is generated and send (4) CS      -.
390         // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
391         // know the per_commitment_point to use for it.
392         //                                       <- (2) commitment_signed delivered
393         // revoke_and_ack                        ->
394         //                                          B should send no response here
395         // (4) commitment_signed delivered       ->
396         //                                       <- RAA/commitment_signed delivered
397         // revoke_and_ack                        ->
398
399         // First nodes[0] generates an update_fee
400         let initial_feerate;
401         {
402                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
403                 initial_feerate = *feerate_lock;
404                 *feerate_lock = initial_feerate + 20;
405         }
406         nodes[0].node.timer_tick_occurred();
407         check_added_monitors!(nodes[0], 1);
408
409         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
410         assert_eq!(events_0.len(), 1);
411         let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
412                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
413                         (update_fee.as_ref().unwrap(), commitment_signed)
414                 },
415                 _ => panic!("Unexpected event"),
416         };
417
418         // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
419         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
420         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
421         let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
422         check_added_monitors!(nodes[1], 1);
423
424         // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
425         // transaction:
426         {
427                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
428                 *feerate_lock = initial_feerate + 40;
429         }
430         nodes[0].node.timer_tick_occurred();
431         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
432         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
433
434         // Create the (3) update_fee message that nodes[0] will generate before it does...
435         let mut update_msg_2 = msgs::UpdateFee {
436                 channel_id: update_msg_1.channel_id.clone(),
437                 feerate_per_kw: (initial_feerate + 30) as u32,
438         };
439
440         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
441
442         update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
443         // Deliver (3)
444         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
445
446         // Deliver (1), generating (3) and (4)
447         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
448         let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
449         check_added_monitors!(nodes[0], 1);
450         assert!(as_second_update.update_add_htlcs.is_empty());
451         assert!(as_second_update.update_fulfill_htlcs.is_empty());
452         assert!(as_second_update.update_fail_htlcs.is_empty());
453         assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
454         // Check that the update_fee newly generated matches what we delivered:
455         assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
456         assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
457
458         // Deliver (2) commitment_signed
459         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
460         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
461         check_added_monitors!(nodes[0], 1);
462         // No commitment_signed so get_event_msg's assert(len == 1) passes
463
464         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
465         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
466         check_added_monitors!(nodes[1], 1);
467
468         // Delever (4)
469         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
470         let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
471         check_added_monitors!(nodes[1], 1);
472
473         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
474         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
475         check_added_monitors!(nodes[0], 1);
476
477         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
478         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
479         // No commitment_signed so get_event_msg's assert(len == 1) passes
480         check_added_monitors!(nodes[0], 1);
481
482         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
483         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
484         check_added_monitors!(nodes[1], 1);
485 }
486
487 fn do_test_sanity_on_in_flight_opens(steps: u8) {
488         // Previously, we had issues deserializing channels when we hadn't connected the first block
489         // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
490         // serialization round-trips and simply do steps towards opening a channel and then drop the
491         // Node objects.
492
493         let chanmon_cfgs = create_chanmon_cfgs(2);
494         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
495         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
496         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
497
498         if steps & 0b1000_0000 != 0{
499                 let block = Block {
500                         header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
501                         txdata: vec![],
502                 };
503                 connect_block(&nodes[0], &block);
504                 connect_block(&nodes[1], &block);
505         }
506
507         if steps & 0x0f == 0 { return; }
508         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
509         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
510
511         if steps & 0x0f == 1 { return; }
512         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
513         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
514
515         if steps & 0x0f == 2 { return; }
516         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
517
518         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
519
520         if steps & 0x0f == 3 { return; }
521         nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
522         check_added_monitors!(nodes[0], 0);
523         let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
524
525         if steps & 0x0f == 4 { return; }
526         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
527         {
528                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
529                 assert_eq!(added_monitors.len(), 1);
530                 assert_eq!(added_monitors[0].0, funding_output);
531                 added_monitors.clear();
532         }
533         let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
534
535         if steps & 0x0f == 5 { return; }
536         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
537         {
538                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
539                 assert_eq!(added_monitors.len(), 1);
540                 assert_eq!(added_monitors[0].0, funding_output);
541                 added_monitors.clear();
542         }
543
544         let events_4 = nodes[0].node.get_and_clear_pending_events();
545         assert_eq!(events_4.len(), 0);
546
547         if steps & 0x0f == 6 { return; }
548         create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
549
550         if steps & 0x0f == 7 { return; }
551         confirm_transaction_at(&nodes[0], &tx, 2);
552         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
553         create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
554 }
555
556 #[test]
557 fn test_sanity_on_in_flight_opens() {
558         do_test_sanity_on_in_flight_opens(0);
559         do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
560         do_test_sanity_on_in_flight_opens(1);
561         do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
562         do_test_sanity_on_in_flight_opens(2);
563         do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
564         do_test_sanity_on_in_flight_opens(3);
565         do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
566         do_test_sanity_on_in_flight_opens(4);
567         do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
568         do_test_sanity_on_in_flight_opens(5);
569         do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
570         do_test_sanity_on_in_flight_opens(6);
571         do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
572         do_test_sanity_on_in_flight_opens(7);
573         do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
574         do_test_sanity_on_in_flight_opens(8);
575         do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
576 }
577
578 #[test]
579 fn test_update_fee_vanilla() {
580         let chanmon_cfgs = create_chanmon_cfgs(2);
581         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
582         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
583         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
584         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
585
586         {
587                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
588                 *feerate_lock += 25;
589         }
590         nodes[0].node.timer_tick_occurred();
591         check_added_monitors!(nodes[0], 1);
592
593         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
594         assert_eq!(events_0.len(), 1);
595         let (update_msg, commitment_signed) = match events_0[0] {
596                         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 } } => {
597                         (update_fee.as_ref(), commitment_signed)
598                 },
599                 _ => panic!("Unexpected event"),
600         };
601         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
602
603         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
604         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
605         check_added_monitors!(nodes[1], 1);
606
607         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
608         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
609         check_added_monitors!(nodes[0], 1);
610
611         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
612         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
613         // No commitment_signed so get_event_msg's assert(len == 1) passes
614         check_added_monitors!(nodes[0], 1);
615
616         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
617         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
618         check_added_monitors!(nodes[1], 1);
619 }
620
621 #[test]
622 fn test_update_fee_that_funder_cannot_afford() {
623         let chanmon_cfgs = create_chanmon_cfgs(2);
624         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
625         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
626         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
627         let channel_value = 5000;
628         let push_sats = 700;
629         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, push_sats * 1000, InitFeatures::known(), InitFeatures::known());
630         let channel_id = chan.2;
631         let secp_ctx = Secp256k1::new();
632         let bs_channel_reserve_sats = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value);
633
634         let opt_anchors = false;
635
636         // Calculate the maximum feerate that A can afford. Note that we don't send an update_fee
637         // CONCURRENT_INBOUND_HTLC_FEE_BUFFER HTLCs before actually running out of local balance, so we
638         // calculate two different feerates here - the expected local limit as well as the expected
639         // remote limit.
640         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;
641         let non_buffer_feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / commitment_tx_base_weight(opt_anchors)) as u32;
642         {
643                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
644                 *feerate_lock = feerate;
645         }
646         nodes[0].node.timer_tick_occurred();
647         check_added_monitors!(nodes[0], 1);
648         let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
649
650         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
651
652         commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
653
654         // Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate set above.
655         {
656                 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
657
658                 //We made sure neither party's funds are below the dust limit and there are no HTLCs here
659                 assert_eq!(commitment_tx.output.len(), 2);
660                 let total_fee: u64 = commit_tx_fee_msat(feerate, 0, opt_anchors) / 1000;
661                 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
662                 actual_fee = channel_value - actual_fee;
663                 assert_eq!(total_fee, actual_fee);
664         }
665
666         {
667                 // Increment the feerate by a small constant, accounting for rounding errors
668                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
669                 *feerate_lock += 4;
670         }
671         nodes[0].node.timer_tick_occurred();
672         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot afford to send new feerate at {}", feerate + 4), 1);
673         check_added_monitors!(nodes[0], 0);
674
675         const INITIAL_COMMITMENT_NUMBER: u64 = 281474976710654;
676
677         // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
678         // needed to sign the new commitment tx and (2) sign the new commitment tx.
679         let (local_revocation_basepoint, local_htlc_basepoint, local_funding) = {
680                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
681                 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
682                 let chan_signer = local_chan.get_signer();
683                 let pubkeys = chan_signer.pubkeys();
684                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
685                  pubkeys.funding_pubkey)
686         };
687         let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point, remote_funding) = {
688                 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
689                 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
690                 let chan_signer = remote_chan.get_signer();
691                 let pubkeys = chan_signer.pubkeys();
692                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
693                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
694                  pubkeys.funding_pubkey)
695         };
696
697         // Assemble the set of keys we can use for signatures for our commitment_signed message.
698         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
699                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
700
701         let res = {
702                 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
703                 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
704                 let local_chan_signer = local_chan.get_signer();
705                 let mut htlcs: Vec<(HTLCOutputInCommitment, ())> = vec![];
706                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
707                         INITIAL_COMMITMENT_NUMBER - 1,
708                         push_sats,
709                         channel_value - push_sats - commit_tx_fee_msat(non_buffer_feerate + 4, 0, opt_anchors) / 1000,
710                         opt_anchors, local_funding, remote_funding,
711                         commit_tx_keys.clone(),
712                         non_buffer_feerate + 4,
713                         &mut htlcs,
714                         &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
715                 );
716                 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
717         };
718
719         let commit_signed_msg = msgs::CommitmentSigned {
720                 channel_id: chan.2,
721                 signature: res.0,
722                 htlc_signatures: res.1
723         };
724
725         let update_fee = msgs::UpdateFee {
726                 channel_id: chan.2,
727                 feerate_per_kw: non_buffer_feerate + 4,
728         };
729
730         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_fee);
731
732         //While producing the commitment_signed response after handling a received update_fee request the
733         //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
734         //Should produce and error.
735         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
736         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
737         check_added_monitors!(nodes[1], 1);
738         check_closed_broadcast!(nodes[1], true);
739         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: String::from("Funding remote cannot afford proposed new fee") });
740 }
741
742 #[test]
743 fn test_update_fee_with_fundee_update_add_htlc() {
744         let chanmon_cfgs = create_chanmon_cfgs(2);
745         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
746         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
747         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
748         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
749
750         // balancing
751         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
752
753         {
754                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
755                 *feerate_lock += 20;
756         }
757         nodes[0].node.timer_tick_occurred();
758         check_added_monitors!(nodes[0], 1);
759
760         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
761         assert_eq!(events_0.len(), 1);
762         let (update_msg, commitment_signed) = match events_0[0] {
763                         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 } } => {
764                         (update_fee.as_ref(), commitment_signed)
765                 },
766                 _ => panic!("Unexpected event"),
767         };
768         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
769         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
770         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
771         check_added_monitors!(nodes[1], 1);
772
773         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 800000);
774
775         // nothing happens since node[1] is in AwaitingRemoteRevoke
776         nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
777         {
778                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
779                 assert_eq!(added_monitors.len(), 0);
780                 added_monitors.clear();
781         }
782         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
783         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
784         // node[1] has nothing to do
785
786         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
787         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
788         check_added_monitors!(nodes[0], 1);
789
790         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
791         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
792         // No commitment_signed so get_event_msg's assert(len == 1) passes
793         check_added_monitors!(nodes[0], 1);
794         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
795         check_added_monitors!(nodes[1], 1);
796         // AwaitingRemoteRevoke ends here
797
798         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
799         assert_eq!(commitment_update.update_add_htlcs.len(), 1);
800         assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
801         assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
802         assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
803         assert_eq!(commitment_update.update_fee.is_none(), true);
804
805         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
806         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
807         check_added_monitors!(nodes[0], 1);
808         let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
809
810         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
811         check_added_monitors!(nodes[1], 1);
812         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
813
814         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
815         check_added_monitors!(nodes[1], 1);
816         let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
817         // No commitment_signed so get_event_msg's assert(len == 1) passes
818
819         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
820         check_added_monitors!(nodes[0], 1);
821         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
822
823         expect_pending_htlcs_forwardable!(nodes[0]);
824
825         let events = nodes[0].node.get_and_clear_pending_events();
826         assert_eq!(events.len(), 1);
827         match events[0] {
828                 Event::PaymentReceived { .. } => { },
829                 _ => panic!("Unexpected event"),
830         };
831
832         claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
833
834         send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
835         send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
836         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
837         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
838         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
839 }
840
841 #[test]
842 fn test_update_fee() {
843         let chanmon_cfgs = create_chanmon_cfgs(2);
844         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
845         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
846         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
847         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
848         let channel_id = chan.2;
849
850         // A                                        B
851         // (1) update_fee/commitment_signed      ->
852         //                                       <- (2) revoke_and_ack
853         //                                       .- send (3) commitment_signed
854         // (4) update_fee/commitment_signed      ->
855         //                                       .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
856         //                                       <- (3) commitment_signed delivered
857         // send (6) revoke_and_ack               -.
858         //                                       <- (5) deliver revoke_and_ack
859         // (6) deliver revoke_and_ack            ->
860         //                                       .- send (7) commitment_signed in response to (4)
861         //                                       <- (7) deliver commitment_signed
862         // revoke_and_ack                        ->
863
864         // Create and deliver (1)...
865         let feerate;
866         {
867                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
868                 feerate = *feerate_lock;
869                 *feerate_lock = feerate + 20;
870         }
871         nodes[0].node.timer_tick_occurred();
872         check_added_monitors!(nodes[0], 1);
873
874         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
875         assert_eq!(events_0.len(), 1);
876         let (update_msg, commitment_signed) = match events_0[0] {
877                         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 } } => {
878                         (update_fee.as_ref(), commitment_signed)
879                 },
880                 _ => panic!("Unexpected event"),
881         };
882         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
883
884         // Generate (2) and (3):
885         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
886         let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
887         check_added_monitors!(nodes[1], 1);
888
889         // Deliver (2):
890         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
891         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
892         check_added_monitors!(nodes[0], 1);
893
894         // Create and deliver (4)...
895         {
896                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
897                 *feerate_lock = feerate + 30;
898         }
899         nodes[0].node.timer_tick_occurred();
900         check_added_monitors!(nodes[0], 1);
901         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
902         assert_eq!(events_0.len(), 1);
903         let (update_msg, commitment_signed) = match events_0[0] {
904                         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 } } => {
905                         (update_fee.as_ref(), commitment_signed)
906                 },
907                 _ => panic!("Unexpected event"),
908         };
909
910         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
911         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
912         check_added_monitors!(nodes[1], 1);
913         // ... creating (5)
914         let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
915         // No commitment_signed so get_event_msg's assert(len == 1) passes
916
917         // Handle (3), creating (6):
918         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
919         check_added_monitors!(nodes[0], 1);
920         let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
921         // No commitment_signed so get_event_msg's assert(len == 1) passes
922
923         // Deliver (5):
924         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
925         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
926         check_added_monitors!(nodes[0], 1);
927
928         // Deliver (6), creating (7):
929         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
930         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
931         assert!(commitment_update.update_add_htlcs.is_empty());
932         assert!(commitment_update.update_fulfill_htlcs.is_empty());
933         assert!(commitment_update.update_fail_htlcs.is_empty());
934         assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
935         assert!(commitment_update.update_fee.is_none());
936         check_added_monitors!(nodes[1], 1);
937
938         // Deliver (7)
939         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
940         check_added_monitors!(nodes[0], 1);
941         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
942         // No commitment_signed so get_event_msg's assert(len == 1) passes
943
944         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
945         check_added_monitors!(nodes[1], 1);
946         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
947
948         assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
949         assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
950         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
951         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
952         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
953 }
954
955 #[test]
956 fn fake_network_test() {
957         // Simple test which builds a network of ChannelManagers, connects them to each other, and
958         // tests that payments get routed and transactions broadcast in semi-reasonable ways.
959         let chanmon_cfgs = create_chanmon_cfgs(4);
960         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
961         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
962         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
963
964         // Create some initial channels
965         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
966         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
967         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
968
969         // Rebalance the network a bit by relaying one payment through all the channels...
970         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
971         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
972         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
973         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
974
975         // Send some more payments
976         send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
977         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
978         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
979
980         // Test failure packets
981         let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
982         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
983
984         // Add a new channel that skips 3
985         let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
986
987         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
988         send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
989         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
990         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
991         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
992         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
993         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
994
995         // Do some rebalance loop payments, simultaneously
996         let mut hops = Vec::with_capacity(3);
997         hops.push(RouteHop {
998                 pubkey: nodes[2].node.get_our_node_id(),
999                 node_features: NodeFeatures::empty(),
1000                 short_channel_id: chan_2.0.contents.short_channel_id,
1001                 channel_features: ChannelFeatures::empty(),
1002                 fee_msat: 0,
1003                 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1004         });
1005         hops.push(RouteHop {
1006                 pubkey: nodes[3].node.get_our_node_id(),
1007                 node_features: NodeFeatures::empty(),
1008                 short_channel_id: chan_3.0.contents.short_channel_id,
1009                 channel_features: ChannelFeatures::empty(),
1010                 fee_msat: 0,
1011                 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1012         });
1013         hops.push(RouteHop {
1014                 pubkey: nodes[1].node.get_our_node_id(),
1015                 node_features: NodeFeatures::known(),
1016                 short_channel_id: chan_4.0.contents.short_channel_id,
1017                 channel_features: ChannelFeatures::known(),
1018                 fee_msat: 1000000,
1019                 cltv_expiry_delta: TEST_FINAL_CLTV,
1020         });
1021         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;
1022         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;
1023         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;
1024
1025         let mut hops = Vec::with_capacity(3);
1026         hops.push(RouteHop {
1027                 pubkey: nodes[3].node.get_our_node_id(),
1028                 node_features: NodeFeatures::empty(),
1029                 short_channel_id: chan_4.0.contents.short_channel_id,
1030                 channel_features: ChannelFeatures::empty(),
1031                 fee_msat: 0,
1032                 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1033         });
1034         hops.push(RouteHop {
1035                 pubkey: nodes[2].node.get_our_node_id(),
1036                 node_features: NodeFeatures::empty(),
1037                 short_channel_id: chan_3.0.contents.short_channel_id,
1038                 channel_features: ChannelFeatures::empty(),
1039                 fee_msat: 0,
1040                 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1041         });
1042         hops.push(RouteHop {
1043                 pubkey: nodes[1].node.get_our_node_id(),
1044                 node_features: NodeFeatures::known(),
1045                 short_channel_id: chan_2.0.contents.short_channel_id,
1046                 channel_features: ChannelFeatures::known(),
1047                 fee_msat: 1000000,
1048                 cltv_expiry_delta: TEST_FINAL_CLTV,
1049         });
1050         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;
1051         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;
1052         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;
1053
1054         // Claim the rebalances...
1055         fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1056         claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1057
1058         // Add a duplicate new channel from 2 to 4
1059         let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1060
1061         // Send some payments across both channels
1062         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1063         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1064         let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1065
1066
1067         route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
1068         let events = nodes[0].node.get_and_clear_pending_msg_events();
1069         assert_eq!(events.len(), 0);
1070         nodes[0].logger.assert_log_regex("lightning::ln::channelmanager".to_string(), regex::Regex::new(r"Cannot send value that would put us over the max HTLC value in flight our peer will accept \(\d+\)").unwrap(), 1);
1071
1072         //TODO: Test that routes work again here as we've been notified that the channel is full
1073
1074         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3);
1075         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4);
1076         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5);
1077
1078         // Close down the channels...
1079         close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1080         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
1081         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1082         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1083         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1084         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1085         close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1086         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1087         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1088         close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1089         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1090         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1091         close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
1092         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1093         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1094 }
1095
1096 #[test]
1097 fn holding_cell_htlc_counting() {
1098         // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1099         // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1100         // commitment dance rounds.
1101         let chanmon_cfgs = create_chanmon_cfgs(3);
1102         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1103         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1104         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1105         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1106         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1107
1108         let mut payments = Vec::new();
1109         for _ in 0..::ln::channel::OUR_MAX_HTLCS {
1110                 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1111                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
1112                 payments.push((payment_preimage, payment_hash));
1113         }
1114         check_added_monitors!(nodes[1], 1);
1115
1116         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1117         assert_eq!(events.len(), 1);
1118         let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1119         assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1120
1121         // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1122         // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1123         // another HTLC.
1124         let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1125         {
1126                 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)), true, APIError::ChannelUnavailable { ref err },
1127                         assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1128                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1129                 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1130         }
1131
1132         // This should also be true if we try to forward a payment.
1133         let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1134         {
1135                 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
1136                 check_added_monitors!(nodes[0], 1);
1137         }
1138
1139         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1140         assert_eq!(events.len(), 1);
1141         let payment_event = SendEvent::from_event(events.pop().unwrap());
1142         assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1143
1144         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1145         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1146         // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1147         // fails), the second will process the resulting failure and fail the HTLC backward.
1148         expect_pending_htlcs_forwardable!(nodes[1]);
1149         expect_pending_htlcs_forwardable!(nodes[1]);
1150         check_added_monitors!(nodes[1], 1);
1151
1152         let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1153         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1154         commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1155
1156         expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1157
1158         // Now forward all the pending HTLCs and claim them back
1159         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1160         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1161         check_added_monitors!(nodes[2], 1);
1162
1163         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1164         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1165         check_added_monitors!(nodes[1], 1);
1166         let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1167
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_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1171
1172         for ref update in as_updates.update_add_htlcs.iter() {
1173                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1174         }
1175         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1176         check_added_monitors!(nodes[2], 1);
1177         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1178         check_added_monitors!(nodes[2], 1);
1179         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1180
1181         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1182         check_added_monitors!(nodes[1], 1);
1183         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1184         check_added_monitors!(nodes[1], 1);
1185         let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1186
1187         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1188         check_added_monitors!(nodes[2], 1);
1189
1190         expect_pending_htlcs_forwardable!(nodes[2]);
1191
1192         let events = nodes[2].node.get_and_clear_pending_events();
1193         assert_eq!(events.len(), payments.len());
1194         for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1195                 match event {
1196                         &Event::PaymentReceived { ref payment_hash, .. } => {
1197                                 assert_eq!(*payment_hash, *hash);
1198                         },
1199                         _ => panic!("Unexpected event"),
1200                 };
1201         }
1202
1203         for (preimage, _) in payments.drain(..) {
1204                 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1205         }
1206
1207         send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1208 }
1209
1210 #[test]
1211 fn duplicate_htlc_test() {
1212         // Test that we accept duplicate payment_hash HTLCs across the network and that
1213         // claiming/failing them are all separate and don't affect each other
1214         let chanmon_cfgs = create_chanmon_cfgs(6);
1215         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1216         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1217         let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1218
1219         // Create some initial channels to route via 3 to 4/5 from 0/1/2
1220         create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
1221         create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1222         create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1223         create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
1224         create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
1225
1226         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1227
1228         *nodes[0].network_payment_count.borrow_mut() -= 1;
1229         assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1230
1231         *nodes[0].network_payment_count.borrow_mut() -= 1;
1232         assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1233
1234         claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1235         fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1236         claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1237 }
1238
1239 #[test]
1240 fn test_duplicate_htlc_different_direction_onchain() {
1241         // Test that ChannelMonitor doesn't generate 2 preimage txn
1242         // when we have 2 HTLCs with same preimage that go across a node
1243         // in opposite directions, even with the same payment secret.
1244         let chanmon_cfgs = create_chanmon_cfgs(2);
1245         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1246         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1247         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1248
1249         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1250
1251         // balancing
1252         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1253
1254         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1255
1256         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1257         let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200).unwrap();
1258         send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1259
1260         // Provide preimage to node 0 by claiming payment
1261         nodes[0].node.claim_funds(payment_preimage);
1262         check_added_monitors!(nodes[0], 1);
1263
1264         // Broadcast node 1 commitment txn
1265         let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1266
1267         assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1268         let mut has_both_htlcs = 0; // check htlcs match ones committed
1269         for outp in remote_txn[0].output.iter() {
1270                 if outp.value == 800_000 / 1000 {
1271                         has_both_htlcs += 1;
1272                 } else if outp.value == 900_000 / 1000 {
1273                         has_both_htlcs += 1;
1274                 }
1275         }
1276         assert_eq!(has_both_htlcs, 2);
1277
1278         mine_transaction(&nodes[0], &remote_txn[0]);
1279         check_added_monitors!(nodes[0], 1);
1280         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
1281         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
1282
1283         let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1284         assert_eq!(claim_txn.len(), 8);
1285
1286         check_spends!(claim_txn[0], remote_txn[0]); // Immediate HTLC claim with preimage
1287
1288         check_spends!(claim_txn[1], chan_1.3); // Alternative commitment tx
1289         check_spends!(claim_txn[2], claim_txn[1]); // HTLC spend in alternative commitment tx
1290
1291         let bump_tx = if claim_txn[1] == claim_txn[4] {
1292                 assert_eq!(claim_txn[1], claim_txn[4]);
1293                 assert_eq!(claim_txn[2], claim_txn[5]);
1294
1295                 check_spends!(claim_txn[7], claim_txn[1]); // HTLC timeout on alternative commitment tx
1296
1297                 check_spends!(claim_txn[3], remote_txn[0]); // HTLC timeout on broadcasted commitment tx
1298                 &claim_txn[3]
1299         } else {
1300                 assert_eq!(claim_txn[1], claim_txn[3]);
1301                 assert_eq!(claim_txn[2], claim_txn[4]);
1302
1303                 check_spends!(claim_txn[5], claim_txn[1]); // HTLC timeout on alternative commitment tx
1304
1305                 check_spends!(claim_txn[7], remote_txn[0]); // HTLC timeout on broadcasted commitment tx
1306
1307                 &claim_txn[7]
1308         };
1309
1310         assert_eq!(claim_txn[0].input.len(), 1);
1311         assert_eq!(bump_tx.input.len(), 1);
1312         assert_eq!(claim_txn[0].input[0].previous_output, bump_tx.input[0].previous_output);
1313
1314         assert_eq!(claim_txn[0].input.len(), 1);
1315         assert_eq!(claim_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1316         assert_eq!(remote_txn[0].output[claim_txn[0].input[0].previous_output.vout as usize].value, 800);
1317
1318         assert_eq!(claim_txn[6].input.len(), 1);
1319         assert_eq!(claim_txn[6].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1320         check_spends!(claim_txn[6], remote_txn[0]);
1321         assert_eq!(remote_txn[0].output[claim_txn[6].input[0].previous_output.vout as usize].value, 900);
1322
1323         let events = nodes[0].node.get_and_clear_pending_msg_events();
1324         assert_eq!(events.len(), 3);
1325         for e in events {
1326                 match e {
1327                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1328                         MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1329                                 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1330                                 assert_eq!(msg.data, "Channel closed because commitment or closing transaction was confirmed on chain.");
1331                         },
1332                         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, .. } } => {
1333                                 assert!(update_add_htlcs.is_empty());
1334                                 assert!(update_fail_htlcs.is_empty());
1335                                 assert_eq!(update_fulfill_htlcs.len(), 1);
1336                                 assert!(update_fail_malformed_htlcs.is_empty());
1337                                 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1338                         },
1339                         _ => panic!("Unexpected event"),
1340                 }
1341         }
1342 }
1343
1344 #[test]
1345 fn test_basic_channel_reserve() {
1346         let chanmon_cfgs = create_chanmon_cfgs(2);
1347         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1348         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1349         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1350         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1351
1352         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1353         let channel_reserve = chan_stat.channel_reserve_msat;
1354
1355         // The 2* and +1 are for the fee spike reserve.
1356         let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], chan.2), 1 + 1, get_opt_anchors!(nodes[0], chan.2));
1357         let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1358         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send + 1);
1359         let err = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).err().unwrap();
1360         match err {
1361                 PaymentSendFailure::AllFailedRetrySafe(ref fails) => {
1362                         match &fails[0] {
1363                                 &APIError::ChannelUnavailable{ref err} =>
1364                                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1365                                 _ => panic!("Unexpected error variant"),
1366                         }
1367                 },
1368                 _ => panic!("Unexpected error variant"),
1369         }
1370         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1371         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);
1372
1373         send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1374 }
1375
1376 #[test]
1377 fn test_fee_spike_violation_fails_htlc() {
1378         let chanmon_cfgs = create_chanmon_cfgs(2);
1379         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1380         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1381         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1382         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1383
1384         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3460001);
1385         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1386         let secp_ctx = Secp256k1::new();
1387         let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1388
1389         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1390
1391         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1392         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &Some(payment_secret), cur_height, &None).unwrap();
1393         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1394         let msg = msgs::UpdateAddHTLC {
1395                 channel_id: chan.2,
1396                 htlc_id: 0,
1397                 amount_msat: htlc_msat,
1398                 payment_hash: payment_hash,
1399                 cltv_expiry: htlc_cltv,
1400                 onion_routing_packet: onion_packet,
1401         };
1402
1403         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1404
1405         // Now manually create the commitment_signed message corresponding to the update_add
1406         // nodes[0] just sent. In the code for construction of this message, "local" refers
1407         // to the sender of the message, and "remote" refers to the receiver.
1408
1409         let feerate_per_kw = get_feerate!(nodes[0], chan.2);
1410
1411         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1412
1413         // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1414         // needed to sign the new commitment tx and (2) sign the new commitment tx.
1415         let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1416                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
1417                 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
1418                 let chan_signer = local_chan.get_signer();
1419                 // Make the signer believe we validated another commitment, so we can release the secret
1420                 chan_signer.get_enforcement_state().last_holder_commitment -= 1;
1421
1422                 let pubkeys = chan_signer.pubkeys();
1423                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1424                  chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1425                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1426                  chan_signer.pubkeys().funding_pubkey)
1427         };
1428         let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1429                 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
1430                 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
1431                 let chan_signer = remote_chan.get_signer();
1432                 let pubkeys = chan_signer.pubkeys();
1433                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1434                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1435                  chan_signer.pubkeys().funding_pubkey)
1436         };
1437
1438         // Assemble the set of keys we can use for signatures for our commitment_signed message.
1439         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1440                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
1441
1442         // Build the remote commitment transaction so we can sign it, and then later use the
1443         // signature for the commitment_signed message.
1444         let local_chan_balance = 1313;
1445
1446         let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1447                 offered: false,
1448                 amount_msat: 3460001,
1449                 cltv_expiry: htlc_cltv,
1450                 payment_hash,
1451                 transaction_output_index: Some(1),
1452         };
1453
1454         let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1455
1456         let res = {
1457                 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
1458                 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
1459                 let local_chan_signer = local_chan.get_signer();
1460                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1461                         commitment_number,
1462                         95000,
1463                         local_chan_balance,
1464                         local_chan.opt_anchors(), local_funding, remote_funding,
1465                         commit_tx_keys.clone(),
1466                         feerate_per_kw,
1467                         &mut vec![(accepted_htlc_info, ())],
1468                         &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1469                 );
1470                 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
1471         };
1472
1473         let commit_signed_msg = msgs::CommitmentSigned {
1474                 channel_id: chan.2,
1475                 signature: res.0,
1476                 htlc_signatures: res.1
1477         };
1478
1479         // Send the commitment_signed message to the nodes[1].
1480         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1481         let _ = nodes[1].node.get_and_clear_pending_msg_events();
1482
1483         // Send the RAA to nodes[1].
1484         let raa_msg = msgs::RevokeAndACK {
1485                 channel_id: chan.2,
1486                 per_commitment_secret: local_secret,
1487                 next_per_commitment_point: next_local_point
1488         };
1489         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1490
1491         let events = nodes[1].node.get_and_clear_pending_msg_events();
1492         assert_eq!(events.len(), 1);
1493         // Make sure the HTLC failed in the way we expect.
1494         match events[0] {
1495                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1496                         assert_eq!(update_fail_htlcs.len(), 1);
1497                         update_fail_htlcs[0].clone()
1498                 },
1499                 _ => panic!("Unexpected event"),
1500         };
1501         nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1502                 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", ::hex::encode(raa_msg.channel_id)), 1);
1503
1504         check_added_monitors!(nodes[1], 2);
1505 }
1506
1507 #[test]
1508 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1509         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1510         // Set the fee rate for the channel very high, to the point where the fundee
1511         // sending any above-dust amount would result in a channel reserve violation.
1512         // In this test we check that we would be prevented from sending an HTLC in
1513         // this situation.
1514         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1515         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1516         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1517         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1518
1519         let opt_anchors = false;
1520
1521         let mut push_amt = 100_000_000;
1522         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1523         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1524
1525         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, InitFeatures::known(), InitFeatures::known());
1526
1527         // Sending exactly enough to hit the reserve amount should be accepted
1528         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1529                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1530         }
1531
1532         // However one more HTLC should be significantly over the reserve amount and fail.
1533         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1534         unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1535                 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1536         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1537         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);
1538 }
1539
1540 #[test]
1541 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1542         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1543         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1544         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1545         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1546         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1547
1548         let opt_anchors = false;
1549
1550         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1551         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1552         // transaction fee with 0 HTLCs (183 sats)).
1553         let mut push_amt = 100_000_000;
1554         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1555         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1556         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, InitFeatures::known(), InitFeatures::known());
1557
1558         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1559         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1560                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1561         }
1562
1563         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 700_000);
1564         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1565         let secp_ctx = Secp256k1::new();
1566         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1567         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1568         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1569         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 700_000, &Some(payment_secret), cur_height, &None).unwrap();
1570         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1571         let msg = msgs::UpdateAddHTLC {
1572                 channel_id: chan.2,
1573                 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1574                 amount_msat: htlc_msat,
1575                 payment_hash: payment_hash,
1576                 cltv_expiry: htlc_cltv,
1577                 onion_routing_packet: onion_packet,
1578         };
1579
1580         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1581         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1582         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);
1583         assert_eq!(nodes[0].node.list_channels().len(), 0);
1584         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1585         assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1586         check_added_monitors!(nodes[0], 1);
1587         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() });
1588 }
1589
1590 #[test]
1591 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1592         // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1593         // calculating our commitment transaction fee (this was previously broken).
1594         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1595         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1596
1597         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1598         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1599         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1600
1601         let opt_anchors = false;
1602
1603         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1604         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1605         // transaction fee with 0 HTLCs (183 sats)).
1606         let mut push_amt = 100_000_000;
1607         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1608         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1609         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt, InitFeatures::known(), InitFeatures::known());
1610
1611         let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1612                 + feerate_per_kw as u64 * htlc_success_tx_weight(opt_anchors) / 1000 * 1000 - 1;
1613         // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1614         // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1615         // commitment transaction fee.
1616         let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1617
1618         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1619         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1620                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1621         }
1622
1623         // One more than the dust amt should fail, however.
1624         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt + 1);
1625         unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1626                 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1627 }
1628
1629 #[test]
1630 fn test_chan_init_feerate_unaffordability() {
1631         // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to
1632         // channel reserve and feerate requirements.
1633         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1634         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1635         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1636         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1637         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1638
1639         let opt_anchors = false;
1640
1641         // Set the push_msat amount such that nodes[0] will not be able to afford to add even a single
1642         // HTLC.
1643         let mut push_amt = 100_000_000;
1644         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1645         assert_eq!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt + 1, 42, None).unwrap_err(),
1646                 APIError::APIMisuseError { err: "Funding amount (356) can't even pay fee for initial commitment transaction fee of 357.".to_string() });
1647
1648         // During open, we don't have a "counterparty channel reserve" to check against, so that
1649         // requirement only comes into play on the open_channel handling side.
1650         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1651         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt, 42, None).unwrap();
1652         let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
1653         open_channel_msg.push_msat += 1;
1654         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel_msg);
1655
1656         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1657         assert_eq!(msg_events.len(), 1);
1658         match msg_events[0] {
1659                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1660                         assert_eq!(msg.data, "Insufficient funding amount for initial reserve");
1661                 },
1662                 _ => panic!("Unexpected event"),
1663         }
1664 }
1665
1666 #[test]
1667 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1668         // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1669         // calculating our counterparty's commitment transaction fee (this was previously broken).
1670         let chanmon_cfgs = create_chanmon_cfgs(2);
1671         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1672         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1673         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1674         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000, InitFeatures::known(), InitFeatures::known());
1675
1676         let payment_amt = 46000; // Dust amount
1677         // In the previous code, these first four payments would succeed.
1678         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1679         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1680         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1681         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1682
1683         // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1684         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1685         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1686         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1687         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1688         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1689
1690         // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1691         // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1692         // transaction fee and therefore perceived this next payment as a channel reserve violation.
1693         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1694 }
1695
1696 #[test]
1697 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1698         let chanmon_cfgs = create_chanmon_cfgs(3);
1699         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1700         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1701         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1702         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1703         let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1704
1705         let feemsat = 239;
1706         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1707         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1708         let feerate = get_feerate!(nodes[0], chan.2);
1709         let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
1710
1711         // Add a 2* and +1 for the fee spike reserve.
1712         let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1713         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;
1714         let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1715
1716         // Add a pending HTLC.
1717         let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1718         let payment_event_1 = {
1719                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1720                 check_added_monitors!(nodes[0], 1);
1721
1722                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1723                 assert_eq!(events.len(), 1);
1724                 SendEvent::from_event(events.remove(0))
1725         };
1726         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1727
1728         // Attempt to trigger a channel reserve violation --> payment failure.
1729         let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2, opt_anchors);
1730         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;
1731         let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1732         let (route_2, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_2);
1733
1734         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1735         let secp_ctx = Secp256k1::new();
1736         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1737         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1738         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1739         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height, &None).unwrap();
1740         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1741         let msg = msgs::UpdateAddHTLC {
1742                 channel_id: chan.2,
1743                 htlc_id: 1,
1744                 amount_msat: htlc_msat + 1,
1745                 payment_hash: our_payment_hash_1,
1746                 cltv_expiry: htlc_cltv,
1747                 onion_routing_packet: onion_packet,
1748         };
1749
1750         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1751         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1752         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1753         assert_eq!(nodes[1].node.list_channels().len(), 1);
1754         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1755         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1756         check_added_monitors!(nodes[1], 1);
1757         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() });
1758 }
1759
1760 #[test]
1761 fn test_inbound_outbound_capacity_is_not_zero() {
1762         let chanmon_cfgs = create_chanmon_cfgs(2);
1763         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1764         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1765         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1766         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1767         let channels0 = node_chanmgrs[0].list_channels();
1768         let channels1 = node_chanmgrs[1].list_channels();
1769         assert_eq!(channels0.len(), 1);
1770         assert_eq!(channels1.len(), 1);
1771
1772         let reserve = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100000);
1773         assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1774         assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1775
1776         assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1777         assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1778 }
1779
1780 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64, opt_anchors: bool) -> u64 {
1781         (commitment_tx_base_weight(opt_anchors) + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1782 }
1783
1784 #[test]
1785 fn test_channel_reserve_holding_cell_htlcs() {
1786         let chanmon_cfgs = create_chanmon_cfgs(3);
1787         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1788         // When this test was written, the default base fee floated based on the HTLC count.
1789         // It is now fixed, so we simply set the fee to the expected value here.
1790         let mut config = test_default_channel_config();
1791         config.channel_options.forwarding_fee_base_msat = 239;
1792         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1793         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1794         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1795         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1796
1797         let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1798         let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1799
1800         let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1801         let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1802
1803         macro_rules! expect_forward {
1804                 ($node: expr) => {{
1805                         let mut events = $node.node.get_and_clear_pending_msg_events();
1806                         assert_eq!(events.len(), 1);
1807                         check_added_monitors!($node, 1);
1808                         let payment_event = SendEvent::from_event(events.remove(0));
1809                         payment_event
1810                 }}
1811         }
1812
1813         let feemsat = 239; // set above
1814         let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1815         let feerate = get_feerate!(nodes[0], chan_1.2);
1816         let opt_anchors = get_opt_anchors!(nodes[0], chan_1.2);
1817
1818         let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1819
1820         // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1821         {
1822                 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_0);
1823                 route.paths[0].last_mut().unwrap().fee_msat += 1;
1824                 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1825                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1826                         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)));
1827                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1828                 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);
1829         }
1830
1831         // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1832         // nodes[0]'s wealth
1833         loop {
1834                 let amt_msat = recv_value_0 + total_fee_msat;
1835                 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1836                 // Also, ensure that each payment has enough to be over the dust limit to
1837                 // ensure it'll be included in each commit tx fee calculation.
1838                 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1839                 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1840                 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1841                         break;
1842                 }
1843                 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0);
1844
1845                 let (stat01_, stat11_, stat12_, stat22_) = (
1846                         get_channel_value_stat!(nodes[0], chan_1.2),
1847                         get_channel_value_stat!(nodes[1], chan_1.2),
1848                         get_channel_value_stat!(nodes[1], chan_2.2),
1849                         get_channel_value_stat!(nodes[2], chan_2.2),
1850                 );
1851
1852                 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1853                 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1854                 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1855                 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1856                 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1857         }
1858
1859         // adding pending output.
1860         // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1861         // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1862         // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1863         // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1864         // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1865         // cases where 1 msat over X amount will cause a payment failure, but anything less than
1866         // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1867         // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1868         // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1869         // policy.
1870         let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1871         let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1872         let amt_msat_1 = recv_value_1 + total_fee_msat;
1873
1874         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);
1875         let payment_event_1 = {
1876                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1877                 check_added_monitors!(nodes[0], 1);
1878
1879                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1880                 assert_eq!(events.len(), 1);
1881                 SendEvent::from_event(events.remove(0))
1882         };
1883         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1884
1885         // channel reserve test with htlc pending output > 0
1886         let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1887         {
1888                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_2 + 1);
1889                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1890                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1891                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1892         }
1893
1894         // split the rest to test holding cell
1895         let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1896         let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1897         let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1898         let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1899         {
1900                 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
1901                 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);
1902         }
1903
1904         // now see if they go through on both sides
1905         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);
1906         // but this will stuck in the holding cell
1907         nodes[0].node.send_payment(&route_21, our_payment_hash_21, &Some(our_payment_secret_21)).unwrap();
1908         check_added_monitors!(nodes[0], 0);
1909         let events = nodes[0].node.get_and_clear_pending_events();
1910         assert_eq!(events.len(), 0);
1911
1912         // test with outbound holding cell amount > 0
1913         {
1914                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22+1);
1915                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1916                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1917                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1918                 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);
1919         }
1920
1921         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);
1922         // this will also stuck in the holding cell
1923         nodes[0].node.send_payment(&route_22, our_payment_hash_22, &Some(our_payment_secret_22)).unwrap();
1924         check_added_monitors!(nodes[0], 0);
1925         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1926         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1927
1928         // flush the pending htlc
1929         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1930         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1931         check_added_monitors!(nodes[1], 1);
1932
1933         // the pending htlc should be promoted to committed
1934         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1935         check_added_monitors!(nodes[0], 1);
1936         let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1937
1938         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1939         let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1940         // No commitment_signed so get_event_msg's assert(len == 1) passes
1941         check_added_monitors!(nodes[0], 1);
1942
1943         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1944         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1945         check_added_monitors!(nodes[1], 1);
1946
1947         expect_pending_htlcs_forwardable!(nodes[1]);
1948
1949         let ref payment_event_11 = expect_forward!(nodes[1]);
1950         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1951         commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1952
1953         expect_pending_htlcs_forwardable!(nodes[2]);
1954         expect_payment_received!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
1955
1956         // flush the htlcs in the holding cell
1957         assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1958         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1959         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1960         commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1961         expect_pending_htlcs_forwardable!(nodes[1]);
1962
1963         let ref payment_event_3 = expect_forward!(nodes[1]);
1964         assert_eq!(payment_event_3.msgs.len(), 2);
1965         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1966         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1967
1968         commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1969         expect_pending_htlcs_forwardable!(nodes[2]);
1970
1971         let events = nodes[2].node.get_and_clear_pending_events();
1972         assert_eq!(events.len(), 2);
1973         match events[0] {
1974                 Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
1975                         assert_eq!(our_payment_hash_21, *payment_hash);
1976                         assert_eq!(recv_value_21, amt);
1977                         match &purpose {
1978                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1979                                         assert!(payment_preimage.is_none());
1980                                         assert_eq!(our_payment_secret_21, *payment_secret);
1981                                 },
1982                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
1983                         }
1984                 },
1985                 _ => panic!("Unexpected event"),
1986         }
1987         match events[1] {
1988                 Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
1989                         assert_eq!(our_payment_hash_22, *payment_hash);
1990                         assert_eq!(recv_value_22, amt);
1991                         match &purpose {
1992                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1993                                         assert!(payment_preimage.is_none());
1994                                         assert_eq!(our_payment_secret_22, *payment_secret);
1995                                 },
1996                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
1997                         }
1998                 },
1999                 _ => panic!("Unexpected event"),
2000         }
2001
2002         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
2003         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
2004         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
2005
2006         let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1, opt_anchors);
2007         let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2008         send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
2009
2010         let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
2011         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);
2012         let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
2013         assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2014         assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2015
2016         let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
2017         assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2018 }
2019
2020 #[test]
2021 fn channel_reserve_in_flight_removes() {
2022         // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2023         // can send to its counterparty, but due to update ordering, the other side may not yet have
2024         // considered those HTLCs fully removed.
2025         // This tests that we don't count HTLCs which will not be included in the next remote
2026         // commitment transaction towards the reserve value (as it implies no commitment transaction
2027         // will be generated which violates the remote reserve value).
2028         // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2029         // To test this we:
2030         //  * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2031         //    you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2032         //    you only consider the value of the first HTLC, it may not),
2033         //  * start routing a third HTLC from A to B,
2034         //  * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2035         //    the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2036         //  * deliver the first fulfill from B
2037         //  * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2038         //    claim,
2039         //  * deliver A's response CS and RAA.
2040         //    This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2041         //    removed it fully. B now has the push_msat plus the first two HTLCs in value.
2042         //  * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2043         //    of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2044         let chanmon_cfgs = create_chanmon_cfgs(2);
2045         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2046         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2047         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2048         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2049
2050         let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
2051         // Route the first two HTLCs.
2052         let (payment_preimage_1, _, _) = route_payment(&nodes[0], &[&nodes[1]], b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000);
2053         let (payment_preimage_2, _, _) = route_payment(&nodes[0], &[&nodes[1]], 20000);
2054
2055         // Start routing the third HTLC (this is just used to get everyone in the right state).
2056         let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
2057         let send_1 = {
2058                 nodes[0].node.send_payment(&route, payment_hash_3, &Some(payment_secret_3)).unwrap();
2059                 check_added_monitors!(nodes[0], 1);
2060                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2061                 assert_eq!(events.len(), 1);
2062                 SendEvent::from_event(events.remove(0))
2063         };
2064
2065         // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2066         // initial fulfill/CS.
2067         assert!(nodes[1].node.claim_funds(payment_preimage_1));
2068         check_added_monitors!(nodes[1], 1);
2069         let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2070
2071         // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2072         // remove the second HTLC when we send the HTLC back from B to A.
2073         assert!(nodes[1].node.claim_funds(payment_preimage_2));
2074         check_added_monitors!(nodes[1], 1);
2075         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2076
2077         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2078         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2079         check_added_monitors!(nodes[0], 1);
2080         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2081         expect_payment_sent_without_paths!(nodes[0], payment_preimage_1);
2082
2083         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2084         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2085         check_added_monitors!(nodes[1], 1);
2086         // B is already AwaitingRAA, so cant generate a CS here
2087         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2088
2089         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2090         check_added_monitors!(nodes[1], 1);
2091         let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2092
2093         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2094         check_added_monitors!(nodes[0], 1);
2095         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2096
2097         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2098         check_added_monitors!(nodes[1], 1);
2099         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2100
2101         // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2102         // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2103         // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2104         // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2105         // on-chain as necessary).
2106         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2107         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2108         check_added_monitors!(nodes[0], 1);
2109         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2110         expect_payment_sent_without_paths!(nodes[0], payment_preimage_2);
2111
2112         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2113         check_added_monitors!(nodes[1], 1);
2114         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2115
2116         expect_pending_htlcs_forwardable!(nodes[1]);
2117         expect_payment_received!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2118
2119         // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2120         // resolve the second HTLC from A's point of view.
2121         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2122         check_added_monitors!(nodes[0], 1);
2123         expect_payment_path_successful!(nodes[0]);
2124         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2125
2126         // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2127         // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2128         let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2129         let send_2 = {
2130                 nodes[1].node.send_payment(&route, payment_hash_4, &Some(payment_secret_4)).unwrap();
2131                 check_added_monitors!(nodes[1], 1);
2132                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2133                 assert_eq!(events.len(), 1);
2134                 SendEvent::from_event(events.remove(0))
2135         };
2136
2137         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2138         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2139         check_added_monitors!(nodes[0], 1);
2140         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2141
2142         // Now just resolve all the outstanding messages/HTLCs for completeness...
2143
2144         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2145         check_added_monitors!(nodes[1], 1);
2146         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2147
2148         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2149         check_added_monitors!(nodes[1], 1);
2150
2151         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2152         check_added_monitors!(nodes[0], 1);
2153         expect_payment_path_successful!(nodes[0]);
2154         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2155
2156         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2157         check_added_monitors!(nodes[1], 1);
2158         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2159
2160         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2161         check_added_monitors!(nodes[0], 1);
2162
2163         expect_pending_htlcs_forwardable!(nodes[0]);
2164         expect_payment_received!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2165
2166         claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2167         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2168 }
2169
2170 #[test]
2171 fn channel_monitor_network_test() {
2172         // Simple test which builds a network of ChannelManagers, connects them to each other, and
2173         // tests that ChannelMonitor is able to recover from various states.
2174         let chanmon_cfgs = create_chanmon_cfgs(5);
2175         let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2176         let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2177         let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2178
2179         // Create some initial channels
2180         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2181         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2182         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
2183         let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
2184
2185         // Make sure all nodes are at the same starting height
2186         connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2187         connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2188         connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2189         connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2190         connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2191
2192         // Rebalance the network a bit by relaying one payment through all the channels...
2193         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2194         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2195         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2196         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2197
2198         // Simple case with no pending HTLCs:
2199         nodes[1].node.force_close_channel(&chan_1.2).unwrap();
2200         check_added_monitors!(nodes[1], 1);
2201         check_closed_broadcast!(nodes[1], true);
2202         {
2203                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2204                 assert_eq!(node_txn.len(), 1);
2205                 mine_transaction(&nodes[0], &node_txn[0]);
2206                 check_added_monitors!(nodes[0], 1);
2207                 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
2208         }
2209         check_closed_broadcast!(nodes[0], true);
2210         assert_eq!(nodes[0].node.list_channels().len(), 0);
2211         assert_eq!(nodes[1].node.list_channels().len(), 1);
2212         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2213         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2214
2215         // One pending HTLC is discarded by the force-close:
2216         let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
2217
2218         // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2219         // broadcasted until we reach the timelock time).
2220         nodes[1].node.force_close_channel(&chan_2.2).unwrap();
2221         check_closed_broadcast!(nodes[1], true);
2222         check_added_monitors!(nodes[1], 1);
2223         {
2224                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2225                 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2226                 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2227                 mine_transaction(&nodes[2], &node_txn[0]);
2228                 check_added_monitors!(nodes[2], 1);
2229                 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
2230         }
2231         check_closed_broadcast!(nodes[2], true);
2232         assert_eq!(nodes[1].node.list_channels().len(), 0);
2233         assert_eq!(nodes[2].node.list_channels().len(), 1);
2234         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2235         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2236
2237         macro_rules! claim_funds {
2238                 ($node: expr, $prev_node: expr, $preimage: expr) => {
2239                         {
2240                                 assert!($node.node.claim_funds($preimage));
2241                                 check_added_monitors!($node, 1);
2242
2243                                 let events = $node.node.get_and_clear_pending_msg_events();
2244                                 assert_eq!(events.len(), 1);
2245                                 match events[0] {
2246                                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2247                                                 assert!(update_add_htlcs.is_empty());
2248                                                 assert!(update_fail_htlcs.is_empty());
2249                                                 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2250                                         },
2251                                         _ => panic!("Unexpected event"),
2252                                 };
2253                         }
2254                 }
2255         }
2256
2257         // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2258         // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2259         nodes[2].node.force_close_channel(&chan_3.2).unwrap();
2260         check_added_monitors!(nodes[2], 1);
2261         check_closed_broadcast!(nodes[2], true);
2262         let node2_commitment_txid;
2263         {
2264                 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2265                 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2266                 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2267                 node2_commitment_txid = node_txn[0].txid();
2268
2269                 // Claim the payment on nodes[3], giving it knowledge of the preimage
2270                 claim_funds!(nodes[3], nodes[2], payment_preimage_1);
2271                 mine_transaction(&nodes[3], &node_txn[0]);
2272                 check_added_monitors!(nodes[3], 1);
2273                 check_preimage_claim(&nodes[3], &node_txn);
2274         }
2275         check_closed_broadcast!(nodes[3], true);
2276         assert_eq!(nodes[2].node.list_channels().len(), 0);
2277         assert_eq!(nodes[3].node.list_channels().len(), 1);
2278         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
2279         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2280
2281         // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2282         // confusing us in the following tests.
2283         let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2284
2285         // One pending HTLC to time out:
2286         let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
2287         // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2288         // buffer space).
2289
2290         let (close_chan_update_1, close_chan_update_2) = {
2291                 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2292                 let events = nodes[3].node.get_and_clear_pending_msg_events();
2293                 assert_eq!(events.len(), 2);
2294                 let close_chan_update_1 = match events[0] {
2295                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2296                                 msg.clone()
2297                         },
2298                         _ => panic!("Unexpected event"),
2299                 };
2300                 match events[1] {
2301                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2302                                 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2303                         },
2304                         _ => panic!("Unexpected event"),
2305                 }
2306                 check_added_monitors!(nodes[3], 1);
2307
2308                 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2309                 {
2310                         let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2311                         node_txn.retain(|tx| {
2312                                 if tx.input[0].previous_output.txid == node2_commitment_txid {
2313                                         false
2314                                 } else { true }
2315                         });
2316                 }
2317
2318                 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2319
2320                 // Claim the payment on nodes[4], giving it knowledge of the preimage
2321                 claim_funds!(nodes[4], nodes[3], payment_preimage_2);
2322
2323                 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2324                 let events = nodes[4].node.get_and_clear_pending_msg_events();
2325                 assert_eq!(events.len(), 2);
2326                 let close_chan_update_2 = match events[0] {
2327                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2328                                 msg.clone()
2329                         },
2330                         _ => panic!("Unexpected event"),
2331                 };
2332                 match events[1] {
2333                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2334                                 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2335                         },
2336                         _ => panic!("Unexpected event"),
2337                 }
2338                 check_added_monitors!(nodes[4], 1);
2339                 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2340
2341                 mine_transaction(&nodes[4], &node_txn[0]);
2342                 check_preimage_claim(&nodes[4], &node_txn);
2343                 (close_chan_update_1, close_chan_update_2)
2344         };
2345         nodes[3].net_graph_msg_handler.handle_channel_update(&close_chan_update_2).unwrap();
2346         nodes[4].net_graph_msg_handler.handle_channel_update(&close_chan_update_1).unwrap();
2347         assert_eq!(nodes[3].node.list_channels().len(), 0);
2348         assert_eq!(nodes[4].node.list_channels().len(), 0);
2349
2350         nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon).unwrap();
2351         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2352         check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed);
2353 }
2354
2355 #[test]
2356 fn test_justice_tx() {
2357         // Test justice txn built on revoked HTLC-Success tx, against both sides
2358         let mut alice_config = UserConfig::default();
2359         alice_config.channel_options.announced_channel = true;
2360         alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
2361         alice_config.own_channel_config.our_to_self_delay = 6 * 24 * 5;
2362         let mut bob_config = UserConfig::default();
2363         bob_config.channel_options.announced_channel = true;
2364         bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
2365         bob_config.own_channel_config.our_to_self_delay = 6 * 24 * 3;
2366         let user_cfgs = [Some(alice_config), Some(bob_config)];
2367         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2368         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2369         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2370         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2371         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2372         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2373         *nodes[0].connect_style.borrow_mut() = ConnectStyle::FullBlockViaListen;
2374         // Create some new channels:
2375         let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2376
2377         // A pending HTLC which will be revoked:
2378         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2379         // Get the will-be-revoked local txn from nodes[0]
2380         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2381         assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2382         assert_eq!(revoked_local_txn[0].input.len(), 1);
2383         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2384         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2385         assert_eq!(revoked_local_txn[1].input.len(), 1);
2386         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2387         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2388         // Revoke the old state
2389         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2390
2391         {
2392                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2393                 {
2394                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2395                         assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2396                         assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2397
2398                         check_spends!(node_txn[0], revoked_local_txn[0]);
2399                         node_txn.swap_remove(0);
2400                         node_txn.truncate(1);
2401                 }
2402                 check_added_monitors!(nodes[1], 1);
2403                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2404                 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2405
2406                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2407                 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2408                 // Verify broadcast of revoked HTLC-timeout
2409                 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2410                 check_added_monitors!(nodes[0], 1);
2411                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2412                 // Broadcast revoked HTLC-timeout on node 1
2413                 mine_transaction(&nodes[1], &node_txn[1]);
2414                 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2415         }
2416         get_announce_close_broadcast_events(&nodes, 0, 1);
2417
2418         assert_eq!(nodes[0].node.list_channels().len(), 0);
2419         assert_eq!(nodes[1].node.list_channels().len(), 0);
2420
2421         // We test justice_tx build by A on B's revoked HTLC-Success tx
2422         // Create some new channels:
2423         let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2424         {
2425                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2426                 node_txn.clear();
2427         }
2428
2429         // A pending HTLC which will be revoked:
2430         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2431         // Get the will-be-revoked local txn from B
2432         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2433         assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2434         assert_eq!(revoked_local_txn[0].input.len(), 1);
2435         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2436         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2437         // Revoke the old state
2438         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2439         {
2440                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2441                 {
2442                         let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2443                         assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2444                         assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2445
2446                         check_spends!(node_txn[0], revoked_local_txn[0]);
2447                         node_txn.swap_remove(0);
2448                 }
2449                 check_added_monitors!(nodes[0], 1);
2450                 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2451
2452                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2453                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2454                 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2455                 check_added_monitors!(nodes[1], 1);
2456                 mine_transaction(&nodes[0], &node_txn[1]);
2457                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2458                 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2459         }
2460         get_announce_close_broadcast_events(&nodes, 0, 1);
2461         assert_eq!(nodes[0].node.list_channels().len(), 0);
2462         assert_eq!(nodes[1].node.list_channels().len(), 0);
2463 }
2464
2465 #[test]
2466 fn revoked_output_claim() {
2467         // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2468         // transaction is broadcast by its counterparty
2469         let chanmon_cfgs = create_chanmon_cfgs(2);
2470         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2471         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2472         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2473         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2474         // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2475         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2476         assert_eq!(revoked_local_txn.len(), 1);
2477         // Only output is the full channel value back to nodes[0]:
2478         assert_eq!(revoked_local_txn[0].output.len(), 1);
2479         // Send a payment through, updating everyone's latest commitment txn
2480         send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2481
2482         // Inform nodes[1] that nodes[0] broadcast a stale tx
2483         mine_transaction(&nodes[1], &revoked_local_txn[0]);
2484         check_added_monitors!(nodes[1], 1);
2485         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2486         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2487         assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2488
2489         check_spends!(node_txn[0], revoked_local_txn[0]);
2490         check_spends!(node_txn[1], chan_1.3);
2491
2492         // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2493         mine_transaction(&nodes[0], &revoked_local_txn[0]);
2494         get_announce_close_broadcast_events(&nodes, 0, 1);
2495         check_added_monitors!(nodes[0], 1);
2496         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2497 }
2498
2499 #[test]
2500 fn claim_htlc_outputs_shared_tx() {
2501         // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2502         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2503         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2504         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2505         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2506         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2507
2508         // Create some new channel:
2509         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2510
2511         // Rebalance the network to generate htlc in the two directions
2512         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
2513         // 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
2514         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2515         let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2516
2517         // Get the will-be-revoked local txn from node[0]
2518         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2519         assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2520         assert_eq!(revoked_local_txn[0].input.len(), 1);
2521         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2522         assert_eq!(revoked_local_txn[1].input.len(), 1);
2523         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2524         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2525         check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2526
2527         //Revoke the old state
2528         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2529
2530         {
2531                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2532                 check_added_monitors!(nodes[0], 1);
2533                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2534                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2535                 check_added_monitors!(nodes[1], 1);
2536                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2537                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2538                 expect_payment_failed!(nodes[1], payment_hash_2, true);
2539
2540                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2541                 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment
2542
2543                 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2544                 check_spends!(node_txn[0], revoked_local_txn[0]);
2545
2546                 let mut witness_lens = BTreeSet::new();
2547                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2548                 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2549                 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2550                 assert_eq!(witness_lens.len(), 3);
2551                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2552                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2553                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2554
2555                 // Next nodes[1] broadcasts its current local tx state:
2556                 assert_eq!(node_txn[1].input.len(), 1);
2557                 assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
2558         }
2559         get_announce_close_broadcast_events(&nodes, 0, 1);
2560         assert_eq!(nodes[0].node.list_channels().len(), 0);
2561         assert_eq!(nodes[1].node.list_channels().len(), 0);
2562 }
2563
2564 #[test]
2565 fn claim_htlc_outputs_single_tx() {
2566         // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2567         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2568         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2569         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2570         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2571         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2572
2573         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2574
2575         // Rebalance the network to generate htlc in the two directions
2576         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
2577         // node[0] is gonna to revoke an old state thus node[1] should be able to claim both offered/received HTLC outputs on top of commitment tx, but this
2578         // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2579         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2580         let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2581
2582         // Get the will-be-revoked local txn from node[0]
2583         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2584
2585         //Revoke the old state
2586         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2587
2588         {
2589                 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2590                 check_added_monitors!(nodes[0], 1);
2591                 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2592                 check_added_monitors!(nodes[1], 1);
2593                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2594                 let mut events = nodes[0].node.get_and_clear_pending_events();
2595                 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2596                 match events[1] {
2597                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2598                         _ => panic!("Unexpected event"),
2599                 }
2600
2601                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2602                 expect_payment_failed!(nodes[1], payment_hash_2, true);
2603
2604                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2605                 assert!(node_txn.len() == 9 || node_txn.len() == 10);
2606
2607                 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2608                 assert_eq!(node_txn[0].input.len(), 1);
2609                 check_spends!(node_txn[0], chan_1.3);
2610                 assert_eq!(node_txn[1].input.len(), 1);
2611                 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2612                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2613                 check_spends!(node_txn[1], node_txn[0]);
2614
2615                 // Justice transactions are indices 1-2-4
2616                 assert_eq!(node_txn[2].input.len(), 1);
2617                 assert_eq!(node_txn[3].input.len(), 1);
2618                 assert_eq!(node_txn[4].input.len(), 1);
2619
2620                 check_spends!(node_txn[2], revoked_local_txn[0]);
2621                 check_spends!(node_txn[3], revoked_local_txn[0]);
2622                 check_spends!(node_txn[4], revoked_local_txn[0]);
2623
2624                 let mut witness_lens = BTreeSet::new();
2625                 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2626                 witness_lens.insert(node_txn[3].input[0].witness.last().unwrap().len());
2627                 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2628                 assert_eq!(witness_lens.len(), 3);
2629                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2630                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2631                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2632         }
2633         get_announce_close_broadcast_events(&nodes, 0, 1);
2634         assert_eq!(nodes[0].node.list_channels().len(), 0);
2635         assert_eq!(nodes[1].node.list_channels().len(), 0);
2636 }
2637
2638 #[test]
2639 fn test_htlc_on_chain_success() {
2640         // Test that in case of a unilateral close onchain, we detect the state of output and pass
2641         // the preimage backward accordingly. So here we test that ChannelManager is
2642         // broadcasting the right event to other nodes in payment path.
2643         // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2644         // A --------------------> B ----------------------> C (preimage)
2645         // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2646         // commitment transaction was broadcast.
2647         // Then, B should learn the preimage from said transactions, attempting to claim backwards
2648         // towards B.
2649         // B should be able to claim via preimage if A then broadcasts its local tx.
2650         // Finally, when A sees B's latest local commitment transaction it should be able to claim
2651         // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2652         // PaymentSent event).
2653
2654         let chanmon_cfgs = create_chanmon_cfgs(3);
2655         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2656         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2657         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2658
2659         // Create some initial channels
2660         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2661         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2662
2663         // Ensure all nodes are at the same height
2664         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2665         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2666         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2667         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2668
2669         // Rebalance the network a bit by relaying one payment through all the channels...
2670         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2671         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2672
2673         let (our_payment_preimage, payment_hash_1, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2674         let (our_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2675
2676         // Broadcast legit commitment tx from C on B's chain
2677         // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2678         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2679         assert_eq!(commitment_tx.len(), 1);
2680         check_spends!(commitment_tx[0], chan_2.3);
2681         nodes[2].node.claim_funds(our_payment_preimage);
2682         nodes[2].node.claim_funds(our_payment_preimage_2);
2683         check_added_monitors!(nodes[2], 2);
2684         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2685         assert!(updates.update_add_htlcs.is_empty());
2686         assert!(updates.update_fail_htlcs.is_empty());
2687         assert!(updates.update_fail_malformed_htlcs.is_empty());
2688         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2689
2690         mine_transaction(&nodes[2], &commitment_tx[0]);
2691         check_closed_broadcast!(nodes[2], true);
2692         check_added_monitors!(nodes[2], 1);
2693         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2694         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)
2695         assert_eq!(node_txn.len(), 5);
2696         assert_eq!(node_txn[0], node_txn[3]);
2697         assert_eq!(node_txn[1], node_txn[4]);
2698         assert_eq!(node_txn[2], commitment_tx[0]);
2699         check_spends!(node_txn[0], commitment_tx[0]);
2700         check_spends!(node_txn[1], commitment_tx[0]);
2701         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2702         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2703         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2704         assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2705         assert_eq!(node_txn[0].lock_time, 0);
2706         assert_eq!(node_txn[1].lock_time, 0);
2707
2708         // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2709         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2710         connect_block(&nodes[1], &Block { header, txdata: node_txn});
2711         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2712         {
2713                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2714                 assert_eq!(added_monitors.len(), 1);
2715                 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2716                 added_monitors.clear();
2717         }
2718         let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2719         assert_eq!(forwarded_events.len(), 3);
2720         match forwarded_events[0] {
2721                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2722                 _ => panic!("Unexpected event"),
2723         }
2724         let chan_id = Some(chan_1.2);
2725         match forwarded_events[1] {
2726                 Event::PaymentForwarded { fee_earned_msat, source_channel_id, claim_from_onchain_tx } => {
2727                         assert_eq!(fee_earned_msat, Some(1000));
2728                         assert_eq!(source_channel_id, chan_id);
2729                         assert_eq!(claim_from_onchain_tx, true);
2730                 },
2731                 _ => panic!()
2732         }
2733         match forwarded_events[2] {
2734                 Event::PaymentForwarded { fee_earned_msat, source_channel_id, claim_from_onchain_tx } => {
2735                         assert_eq!(fee_earned_msat, Some(1000));
2736                         assert_eq!(source_channel_id, chan_id);
2737                         assert_eq!(claim_from_onchain_tx, true);
2738                 },
2739                 _ => panic!()
2740         }
2741         let events = nodes[1].node.get_and_clear_pending_msg_events();
2742         {
2743                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2744                 assert_eq!(added_monitors.len(), 2);
2745                 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2746                 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2747                 added_monitors.clear();
2748         }
2749         assert_eq!(events.len(), 3);
2750         match events[0] {
2751                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2752                 _ => panic!("Unexpected event"),
2753         }
2754         match events[1] {
2755                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2756                 _ => panic!("Unexpected event"),
2757         }
2758
2759         match events[2] {
2760                 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, .. } } => {
2761                         assert!(update_add_htlcs.is_empty());
2762                         assert!(update_fail_htlcs.is_empty());
2763                         assert_eq!(update_fulfill_htlcs.len(), 1);
2764                         assert!(update_fail_malformed_htlcs.is_empty());
2765                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2766                 },
2767                 _ => panic!("Unexpected event"),
2768         };
2769         macro_rules! check_tx_local_broadcast {
2770                 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2771                         let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2772                         assert_eq!(node_txn.len(), 3);
2773                         // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2774                         // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2775                         check_spends!(node_txn[1], $commitment_tx);
2776                         check_spends!(node_txn[2], $commitment_tx);
2777                         assert_ne!(node_txn[1].lock_time, 0);
2778                         assert_ne!(node_txn[2].lock_time, 0);
2779                         if $htlc_offered {
2780                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2781                                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2782                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2783                                 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2784                         } else {
2785                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2786                                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2787                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2788                                 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2789                         }
2790                         check_spends!(node_txn[0], $chan_tx);
2791                         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2792                         node_txn.clear();
2793                 } }
2794         }
2795         // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2796         // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2797         // timeout-claim of the output that nodes[2] just claimed via success.
2798         check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2799
2800         // Broadcast legit commitment tx from A on B's chain
2801         // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
2802         let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2803         check_spends!(node_a_commitment_tx[0], chan_1.3);
2804         mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2805         check_closed_broadcast!(nodes[1], true);
2806         check_added_monitors!(nodes[1], 1);
2807         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2808         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2809         assert_eq!(node_txn.len(), 6); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 3 (HTLC-Success, 2* RBF bumps of above HTLC txn)
2810         let commitment_spend =
2811                 if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2812                         check_spends!(node_txn[1], commitment_tx[0]);
2813                         check_spends!(node_txn[2], commitment_tx[0]);
2814                         assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2815                         &node_txn[0]
2816                 } else {
2817                         check_spends!(node_txn[0], commitment_tx[0]);
2818                         check_spends!(node_txn[1], commitment_tx[0]);
2819                         assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2820                         &node_txn[2]
2821                 };
2822
2823         check_spends!(commitment_spend, node_a_commitment_tx[0]);
2824         assert_eq!(commitment_spend.input.len(), 2);
2825         assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2826         assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2827         assert_eq!(commitment_spend.lock_time, 0);
2828         assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2829         check_spends!(node_txn[3], chan_1.3);
2830         assert_eq!(node_txn[3].input[0].witness.clone().last().unwrap().len(), 71);
2831         check_spends!(node_txn[4], node_txn[3]);
2832         check_spends!(node_txn[5], node_txn[3]);
2833         // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2834         // we already checked the same situation with A.
2835
2836         // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2837         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2838         connect_block(&nodes[0], &Block { header, txdata: vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()] });
2839         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2840         check_closed_broadcast!(nodes[0], true);
2841         check_added_monitors!(nodes[0], 1);
2842         let events = nodes[0].node.get_and_clear_pending_events();
2843         assert_eq!(events.len(), 5);
2844         let mut first_claimed = false;
2845         for event in events {
2846                 match event {
2847                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
2848                                 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
2849                                         assert!(!first_claimed);
2850                                         first_claimed = true;
2851                                 } else {
2852                                         assert_eq!(payment_preimage, our_payment_preimage_2);
2853                                         assert_eq!(payment_hash, payment_hash_2);
2854                                 }
2855                         },
2856                         Event::PaymentPathSuccessful { .. } => {},
2857                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
2858                         _ => panic!("Unexpected event"),
2859                 }
2860         }
2861         check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0], chan_1.3);
2862 }
2863
2864 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2865         // Test that in case of a unilateral close onchain, we detect the state of output and
2866         // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2867         // broadcasting the right event to other nodes in payment path.
2868         // A ------------------> B ----------------------> C (timeout)
2869         //    B's commitment tx                 C's commitment tx
2870         //            \                                  \
2871         //         B's HTLC timeout tx               B's timeout tx
2872
2873         let chanmon_cfgs = create_chanmon_cfgs(3);
2874         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2875         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2876         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2877         *nodes[0].connect_style.borrow_mut() = connect_style;
2878         *nodes[1].connect_style.borrow_mut() = connect_style;
2879         *nodes[2].connect_style.borrow_mut() = connect_style;
2880
2881         // Create some intial channels
2882         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2883         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2884
2885         // Rebalance the network a bit by relaying one payment thorugh all the channels...
2886         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2887         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2888
2889         let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2890
2891         // Broadcast legit commitment tx from C on B's chain
2892         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2893         check_spends!(commitment_tx[0], chan_2.3);
2894         nodes[2].node.fail_htlc_backwards(&payment_hash);
2895         check_added_monitors!(nodes[2], 0);
2896         expect_pending_htlcs_forwardable!(nodes[2]);
2897         check_added_monitors!(nodes[2], 1);
2898
2899         let events = nodes[2].node.get_and_clear_pending_msg_events();
2900         assert_eq!(events.len(), 1);
2901         match events[0] {
2902                 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, .. } } => {
2903                         assert!(update_add_htlcs.is_empty());
2904                         assert!(!update_fail_htlcs.is_empty());
2905                         assert!(update_fulfill_htlcs.is_empty());
2906                         assert!(update_fail_malformed_htlcs.is_empty());
2907                         assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2908                 },
2909                 _ => panic!("Unexpected event"),
2910         };
2911         mine_transaction(&nodes[2], &commitment_tx[0]);
2912         check_closed_broadcast!(nodes[2], true);
2913         check_added_monitors!(nodes[2], 1);
2914         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2915         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2916         assert_eq!(node_txn.len(), 1);
2917         check_spends!(node_txn[0], chan_2.3);
2918         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2919
2920         // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2921         // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2922         connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2923         mine_transaction(&nodes[1], &commitment_tx[0]);
2924         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2925         let timeout_tx;
2926         {
2927                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2928                 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
2929                 assert_eq!(node_txn[0], node_txn[3]);
2930                 assert_eq!(node_txn[1], node_txn[4]);
2931
2932                 check_spends!(node_txn[2], commitment_tx[0]);
2933                 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2934
2935                 check_spends!(node_txn[0], chan_2.3);
2936                 check_spends!(node_txn[1], node_txn[0]);
2937                 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2938                 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2939
2940                 timeout_tx = node_txn[2].clone();
2941                 node_txn.clear();
2942         }
2943
2944         mine_transaction(&nodes[1], &timeout_tx);
2945         check_added_monitors!(nodes[1], 1);
2946         check_closed_broadcast!(nodes[1], true);
2947         {
2948                 // B will rebroadcast a fee-bumped timeout transaction here.
2949                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2950                 assert_eq!(node_txn.len(), 1);
2951                 check_spends!(node_txn[0], commitment_tx[0]);
2952         }
2953
2954         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2955         {
2956                 // B may rebroadcast its own holder commitment transaction here, as a safeguard against
2957                 // some incredibly unlikely partial-eclipse-attack scenarios. That said, because the
2958                 // original commitment_tx[0] (also spending chan_2.3) has reached ANTI_REORG_DELAY B really
2959                 // shouldn't broadcast anything here, and in some connect style scenarios we do not.
2960                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2961                 if node_txn.len() == 1 {
2962                         check_spends!(node_txn[0], chan_2.3);
2963                 } else {
2964                         assert_eq!(node_txn.len(), 0);
2965                 }
2966         }
2967
2968         expect_pending_htlcs_forwardable!(nodes[1]);
2969         check_added_monitors!(nodes[1], 1);
2970         let events = nodes[1].node.get_and_clear_pending_msg_events();
2971         assert_eq!(events.len(), 1);
2972         match events[0] {
2973                 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, .. } } => {
2974                         assert!(update_add_htlcs.is_empty());
2975                         assert!(!update_fail_htlcs.is_empty());
2976                         assert!(update_fulfill_htlcs.is_empty());
2977                         assert!(update_fail_malformed_htlcs.is_empty());
2978                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2979                 },
2980                 _ => panic!("Unexpected event"),
2981         };
2982
2983         // Broadcast legit commitment tx from B on A's chain
2984         let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
2985         check_spends!(commitment_tx[0], chan_1.3);
2986
2987         mine_transaction(&nodes[0], &commitment_tx[0]);
2988         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2989
2990         check_closed_broadcast!(nodes[0], true);
2991         check_added_monitors!(nodes[0], 1);
2992         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2993         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 commitment tx, ChannelMonitor : 1 timeout tx
2994         assert_eq!(node_txn.len(), 2);
2995         check_spends!(node_txn[0], chan_1.3);
2996         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2997         check_spends!(node_txn[1], commitment_tx[0]);
2998         assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2999 }
3000
3001 #[test]
3002 fn test_htlc_on_chain_timeout() {
3003         do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
3004         do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
3005         do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
3006 }
3007
3008 #[test]
3009 fn test_simple_commitment_revoked_fail_backward() {
3010         // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3011         // and fail backward accordingly.
3012
3013         let chanmon_cfgs = create_chanmon_cfgs(3);
3014         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3015         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3016         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3017
3018         // Create some initial channels
3019         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3020         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3021
3022         let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3023         // Get the will-be-revoked local txn from nodes[2]
3024         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3025         // Revoke the old state
3026         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3027
3028         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3029
3030         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3031         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3032         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3033         check_added_monitors!(nodes[1], 1);
3034         check_closed_broadcast!(nodes[1], true);
3035
3036         expect_pending_htlcs_forwardable!(nodes[1]);
3037         check_added_monitors!(nodes[1], 1);
3038         let events = nodes[1].node.get_and_clear_pending_msg_events();
3039         assert_eq!(events.len(), 1);
3040         match events[0] {
3041                 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, .. } } => {
3042                         assert!(update_add_htlcs.is_empty());
3043                         assert_eq!(update_fail_htlcs.len(), 1);
3044                         assert!(update_fulfill_htlcs.is_empty());
3045                         assert!(update_fail_malformed_htlcs.is_empty());
3046                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3047
3048                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3049                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3050                         expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3051                 },
3052                 _ => panic!("Unexpected event"),
3053         }
3054 }
3055
3056 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3057         // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3058         // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3059         // commitment transaction anymore.
3060         // To do this, we have the peer which will broadcast a revoked commitment transaction send
3061         // a number of update_fail/commitment_signed updates without ever sending the RAA in
3062         // response to our commitment_signed. This is somewhat misbehavior-y, though not
3063         // technically disallowed and we should probably handle it reasonably.
3064         // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3065         // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3066         // transactions:
3067         // * Once we move it out of our holding cell/add it, we will immediately include it in a
3068         //   commitment_signed (implying it will be in the latest remote commitment transaction).
3069         // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3070         //   and once they revoke the previous commitment transaction (allowing us to send a new
3071         //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3072         let chanmon_cfgs = create_chanmon_cfgs(3);
3073         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3074         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3075         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3076
3077         // Create some initial channels
3078         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3079         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3080
3081         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 });
3082         // Get the will-be-revoked local txn from nodes[2]
3083         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3084         assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3085         // Revoke the old state
3086         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3087
3088         let value = if use_dust {
3089                 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3090                 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3091                 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3092         } else { 3000000 };
3093
3094         let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3095         let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3096         let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3097
3098         assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash));
3099         expect_pending_htlcs_forwardable!(nodes[2]);
3100         check_added_monitors!(nodes[2], 1);
3101         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3102         assert!(updates.update_add_htlcs.is_empty());
3103         assert!(updates.update_fulfill_htlcs.is_empty());
3104         assert!(updates.update_fail_malformed_htlcs.is_empty());
3105         assert_eq!(updates.update_fail_htlcs.len(), 1);
3106         assert!(updates.update_fee.is_none());
3107         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3108         let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3109         // Drop the last RAA from 3 -> 2
3110
3111         assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash));
3112         expect_pending_htlcs_forwardable!(nodes[2]);
3113         check_added_monitors!(nodes[2], 1);
3114         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3115         assert!(updates.update_add_htlcs.is_empty());
3116         assert!(updates.update_fulfill_htlcs.is_empty());
3117         assert!(updates.update_fail_malformed_htlcs.is_empty());
3118         assert_eq!(updates.update_fail_htlcs.len(), 1);
3119         assert!(updates.update_fee.is_none());
3120         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3121         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3122         check_added_monitors!(nodes[1], 1);
3123         // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3124         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3125         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3126         check_added_monitors!(nodes[2], 1);
3127
3128         assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash));
3129         expect_pending_htlcs_forwardable!(nodes[2]);
3130         check_added_monitors!(nodes[2], 1);
3131         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3132         assert!(updates.update_add_htlcs.is_empty());
3133         assert!(updates.update_fulfill_htlcs.is_empty());
3134         assert!(updates.update_fail_malformed_htlcs.is_empty());
3135         assert_eq!(updates.update_fail_htlcs.len(), 1);
3136         assert!(updates.update_fee.is_none());
3137         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3138         // At this point first_payment_hash has dropped out of the latest two commitment
3139         // transactions that nodes[1] is tracking...
3140         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3141         check_added_monitors!(nodes[1], 1);
3142         // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3143         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3144         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3145         check_added_monitors!(nodes[2], 1);
3146
3147         // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3148         // on nodes[2]'s RAA.
3149         let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3150         nodes[1].node.send_payment(&route, fourth_payment_hash, &Some(fourth_payment_secret)).unwrap();
3151         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3152         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3153         check_added_monitors!(nodes[1], 0);
3154
3155         if deliver_bs_raa {
3156                 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3157                 // One monitor for the new revocation preimage, no second on as we won't generate a new
3158                 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3159                 check_added_monitors!(nodes[1], 1);
3160                 let events = nodes[1].node.get_and_clear_pending_events();
3161                 assert_eq!(events.len(), 1);
3162                 match events[0] {
3163                         Event::PendingHTLCsForwardable { .. } => { },
3164                         _ => panic!("Unexpected event"),
3165                 };
3166                 // Deliberately don't process the pending fail-back so they all fail back at once after
3167                 // block connection just like the !deliver_bs_raa case
3168         }
3169
3170         let mut failed_htlcs = HashSet::new();
3171         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3172
3173         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3174         check_added_monitors!(nodes[1], 1);
3175         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3176         assert!(ANTI_REORG_DELAY > PAYMENT_EXPIRY_BLOCKS); // We assume payments will also expire
3177
3178         let events = nodes[1].node.get_and_clear_pending_events();
3179         assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 4 });
3180         match events[0] {
3181                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3182                 _ => panic!("Unexepected event"),
3183         }
3184         match events[1] {
3185                 Event::PaymentPathFailed { ref payment_hash, .. } => {
3186                         assert_eq!(*payment_hash, fourth_payment_hash);
3187                 },
3188                 _ => panic!("Unexpected event"),
3189         }
3190         if !deliver_bs_raa {
3191                 match events[2] {
3192                         Event::PaymentFailed { ref payment_hash, .. } => {
3193                                 assert_eq!(*payment_hash, fourth_payment_hash);
3194                         },
3195                         _ => panic!("Unexpected event"),
3196                 }
3197                 match events[3] {
3198                         Event::PendingHTLCsForwardable { .. } => { },
3199                         _ => panic!("Unexpected event"),
3200                 };
3201         }
3202         nodes[1].node.process_pending_htlc_forwards();
3203         check_added_monitors!(nodes[1], 1);
3204
3205         let events = nodes[1].node.get_and_clear_pending_msg_events();
3206         assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3207         match events[if deliver_bs_raa { 1 } else { 0 }] {
3208                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3209                 _ => panic!("Unexpected event"),
3210         }
3211         match events[if deliver_bs_raa { 2 } else { 1 }] {
3212                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3213                         assert_eq!(channel_id, chan_2.2);
3214                         assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3215                 },
3216                 _ => panic!("Unexpected event"),
3217         }
3218         if deliver_bs_raa {
3219                 match events[0] {
3220                         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, .. } } => {
3221                                 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3222                                 assert_eq!(update_add_htlcs.len(), 1);
3223                                 assert!(update_fulfill_htlcs.is_empty());
3224                                 assert!(update_fail_htlcs.is_empty());
3225                                 assert!(update_fail_malformed_htlcs.is_empty());
3226                         },
3227                         _ => panic!("Unexpected event"),
3228                 }
3229         }
3230         match events[if deliver_bs_raa { 3 } else { 2 }] {
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, ref commitment_signed, .. } } => {
3232                         assert!(update_add_htlcs.is_empty());
3233                         assert_eq!(update_fail_htlcs.len(), 3);
3234                         assert!(update_fulfill_htlcs.is_empty());
3235                         assert!(update_fail_malformed_htlcs.is_empty());
3236                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3237
3238                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3239                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3240                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3241
3242                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3243
3244                         let events = nodes[0].node.get_and_clear_pending_events();
3245                         assert_eq!(events.len(), 3);
3246                         match events[0] {
3247                                 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3248                                         assert!(failed_htlcs.insert(payment_hash.0));
3249                                         // If we delivered B's RAA we got an unknown preimage error, not something
3250                                         // that we should update our routing table for.
3251                                         if !deliver_bs_raa {
3252                                                 assert!(network_update.is_some());
3253                                         }
3254                                 },
3255                                 _ => panic!("Unexpected event"),
3256                         }
3257                         match events[1] {
3258                                 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3259                                         assert!(failed_htlcs.insert(payment_hash.0));
3260                                         assert!(network_update.is_some());
3261                                 },
3262                                 _ => panic!("Unexpected event"),
3263                         }
3264                         match events[2] {
3265                                 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3266                                         assert!(failed_htlcs.insert(payment_hash.0));
3267                                         assert!(network_update.is_some());
3268                                 },
3269                                 _ => panic!("Unexpected event"),
3270                         }
3271                 },
3272                 _ => panic!("Unexpected event"),
3273         }
3274
3275         assert!(failed_htlcs.contains(&first_payment_hash.0));
3276         assert!(failed_htlcs.contains(&second_payment_hash.0));
3277         assert!(failed_htlcs.contains(&third_payment_hash.0));
3278 }
3279
3280 #[test]
3281 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3282         do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3283         do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3284         do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3285         do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3286 }
3287
3288 #[test]
3289 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3290         do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3291         do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3292         do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3293         do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3294 }
3295
3296 #[test]
3297 fn fail_backward_pending_htlc_upon_channel_failure() {
3298         let chanmon_cfgs = create_chanmon_cfgs(2);
3299         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3300         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3301         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3302         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
3303
3304         // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3305         {
3306                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3307                 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
3308                 check_added_monitors!(nodes[0], 1);
3309
3310                 let payment_event = {
3311                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3312                         assert_eq!(events.len(), 1);
3313                         SendEvent::from_event(events.remove(0))
3314                 };
3315                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3316                 assert_eq!(payment_event.msgs.len(), 1);
3317         }
3318
3319         // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3320         let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3321         {
3322                 nodes[0].node.send_payment(&route, failed_payment_hash, &Some(failed_payment_secret)).unwrap();
3323                 check_added_monitors!(nodes[0], 0);
3324
3325                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3326         }
3327
3328         // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3329         {
3330                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3331
3332                 let secp_ctx = Secp256k1::new();
3333                 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3334                 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3335                 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &Some(payment_secret), current_height, &None).unwrap();
3336                 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3337                 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3338
3339                 // Send a 0-msat update_add_htlc to fail the channel.
3340                 let update_add_htlc = msgs::UpdateAddHTLC {
3341                         channel_id: chan.2,
3342                         htlc_id: 0,
3343                         amount_msat: 0,
3344                         payment_hash,
3345                         cltv_expiry,
3346                         onion_routing_packet,
3347                 };
3348                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3349         }
3350         let events = nodes[0].node.get_and_clear_pending_events();
3351         assert_eq!(events.len(), 2);
3352         // Check that Alice fails backward the pending HTLC from the second payment.
3353         match events[0] {
3354                 Event::PaymentPathFailed { payment_hash, .. } => {
3355                         assert_eq!(payment_hash, failed_payment_hash);
3356                 },
3357                 _ => panic!("Unexpected event"),
3358         }
3359         match events[1] {
3360                 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3361                         assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3362                 },
3363                 _ => panic!("Unexpected event {:?}", events[1]),
3364         }
3365         check_closed_broadcast!(nodes[0], true);
3366         check_added_monitors!(nodes[0], 1);
3367 }
3368
3369 #[test]
3370 fn test_htlc_ignore_latest_remote_commitment() {
3371         // Test that HTLC transactions spending the latest remote commitment transaction are simply
3372         // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3373         let chanmon_cfgs = create_chanmon_cfgs(2);
3374         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3375         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3376         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3377         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3378
3379         route_payment(&nodes[0], &[&nodes[1]], 10000000);
3380         nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id).unwrap();
3381         connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3382         check_closed_broadcast!(nodes[0], true);
3383         check_added_monitors!(nodes[0], 1);
3384         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
3385
3386         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3387         assert_eq!(node_txn.len(), 3);
3388         assert_eq!(node_txn[0], node_txn[1]);
3389
3390         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3391         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3392         check_closed_broadcast!(nodes[1], true);
3393         check_added_monitors!(nodes[1], 1);
3394         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3395
3396         // Duplicate the connect_block call since this may happen due to other listeners
3397         // registering new transactions
3398         header.prev_blockhash = header.block_hash();
3399         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[2].clone()]});
3400 }
3401
3402 #[test]
3403 fn test_force_close_fail_back() {
3404         // Check which HTLCs are failed-backwards on channel force-closure
3405         let chanmon_cfgs = create_chanmon_cfgs(3);
3406         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3407         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3408         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3409         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3410         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3411
3412         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3413
3414         let mut payment_event = {
3415                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
3416                 check_added_monitors!(nodes[0], 1);
3417
3418                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3419                 assert_eq!(events.len(), 1);
3420                 SendEvent::from_event(events.remove(0))
3421         };
3422
3423         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3424         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3425
3426         expect_pending_htlcs_forwardable!(nodes[1]);
3427
3428         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3429         assert_eq!(events_2.len(), 1);
3430         payment_event = SendEvent::from_event(events_2.remove(0));
3431         assert_eq!(payment_event.msgs.len(), 1);
3432
3433         check_added_monitors!(nodes[1], 1);
3434         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3435         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3436         check_added_monitors!(nodes[2], 1);
3437         let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3438
3439         // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3440         // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3441         // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3442
3443         nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id).unwrap();
3444         check_closed_broadcast!(nodes[2], true);
3445         check_added_monitors!(nodes[2], 1);
3446         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
3447         let tx = {
3448                 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3449                 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3450                 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3451                 // back to nodes[1] upon timeout otherwise.
3452                 assert_eq!(node_txn.len(), 1);
3453                 node_txn.remove(0)
3454         };
3455
3456         mine_transaction(&nodes[1], &tx);
3457
3458         // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3459         check_closed_broadcast!(nodes[1], true);
3460         check_added_monitors!(nodes[1], 1);
3461         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3462
3463         // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3464         {
3465                 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3466                         .provide_payment_preimage(&our_payment_hash, &our_payment_preimage, &node_cfgs[2].tx_broadcaster, &node_cfgs[2].fee_estimator, &node_cfgs[2].logger);
3467         }
3468         mine_transaction(&nodes[2], &tx);
3469         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3470         assert_eq!(node_txn.len(), 1);
3471         assert_eq!(node_txn[0].input.len(), 1);
3472         assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3473         assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3474         assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3475
3476         check_spends!(node_txn[0], tx);
3477 }
3478
3479 #[test]
3480 fn test_dup_events_on_peer_disconnect() {
3481         // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3482         // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3483         // as we used to generate the event immediately upon receipt of the payment preimage in the
3484         // update_fulfill_htlc message.
3485
3486         let chanmon_cfgs = create_chanmon_cfgs(2);
3487         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3488         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3489         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3490         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3491
3492         let payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 1000000).0;
3493
3494         assert!(nodes[1].node.claim_funds(payment_preimage));
3495         check_added_monitors!(nodes[1], 1);
3496         let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3497         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3498         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
3499
3500         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3501         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3502
3503         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3504         expect_payment_path_successful!(nodes[0]);
3505 }
3506
3507 #[test]
3508 fn test_peer_disconnected_before_funding_broadcasted() {
3509         // Test that channels are closed with `ClosureReason::DisconnectedPeer` if the peer disconnects
3510         // before the funding transaction has been broadcasted.
3511         let chanmon_cfgs = create_chanmon_cfgs(2);
3512         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3513         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3514         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3515
3516         // Open a channel between `nodes[0]` and `nodes[1]`, for which the funding transaction is never
3517         // broadcasted, even though it's created by `nodes[0]`.
3518         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();
3519         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
3520         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
3521         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
3522         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
3523
3524         let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], 1_000_000, 42);
3525         assert_eq!(temporary_channel_id, expected_temporary_channel_id);
3526
3527         assert!(nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).is_ok());
3528
3529         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
3530         assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
3531
3532         // Even though the funding transaction is created by `nodes[0]`, the `FundingCreated` msg is
3533         // never sent to `nodes[1]`, and therefore the tx is never signed by either party nor
3534         // broadcasted.
3535         {
3536                 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
3537         }
3538
3539         // Ensure that the channel is closed with `ClosureReason::DisconnectedPeer` when the peers are
3540         // disconnected before the funding transaction was broadcasted.
3541         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3542         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3543
3544         check_closed_event!(nodes[0], 1, ClosureReason::DisconnectedPeer);
3545         check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
3546 }
3547
3548 #[test]
3549 fn test_simple_peer_disconnect() {
3550         // Test that we can reconnect when there are no lost messages
3551         let chanmon_cfgs = create_chanmon_cfgs(3);
3552         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3553         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3554         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3555         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3556         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3557
3558         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3559         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3560         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3561
3562         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3563         let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3564         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3565         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3566
3567         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3568         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3569         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3570
3571         let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3572         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3573         let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3574         let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3575
3576         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3577         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3578
3579         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3580         fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3581
3582         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3583         {
3584                 let events = nodes[0].node.get_and_clear_pending_events();
3585                 assert_eq!(events.len(), 3);
3586                 match events[0] {
3587                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3588                                 assert_eq!(payment_preimage, payment_preimage_3);
3589                                 assert_eq!(payment_hash, payment_hash_3);
3590                         },
3591                         _ => panic!("Unexpected event"),
3592                 }
3593                 match events[1] {
3594                         Event::PaymentPathFailed { payment_hash, rejected_by_dest, .. } => {
3595                                 assert_eq!(payment_hash, payment_hash_5);
3596                                 assert!(rejected_by_dest);
3597                         },
3598                         _ => panic!("Unexpected event"),
3599                 }
3600                 match events[2] {
3601                         Event::PaymentPathSuccessful { .. } => {},
3602                         _ => panic!("Unexpected event"),
3603                 }
3604         }
3605
3606         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3607         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3608 }
3609
3610 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3611         // Test that we can reconnect when in-flight HTLC updates get dropped
3612         let chanmon_cfgs = create_chanmon_cfgs(2);
3613         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3614         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3615         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3616
3617         let mut as_funding_locked = None;
3618         if messages_delivered == 0 {
3619                 let (funding_locked, _, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3620                 as_funding_locked = Some(funding_locked);
3621                 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
3622                 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3623                 // it before the channel_reestablish message.
3624         } else {
3625                 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3626         }
3627
3628         let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3629
3630         let payment_event = {
3631                 nodes[0].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)).unwrap();
3632                 check_added_monitors!(nodes[0], 1);
3633
3634                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3635                 assert_eq!(events.len(), 1);
3636                 SendEvent::from_event(events.remove(0))
3637         };
3638         assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3639
3640         if messages_delivered < 2 {
3641                 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3642         } else {
3643                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3644                 if messages_delivered >= 3 {
3645                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3646                         check_added_monitors!(nodes[1], 1);
3647                         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3648
3649                         if messages_delivered >= 4 {
3650                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3651                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3652                                 check_added_monitors!(nodes[0], 1);
3653
3654                                 if messages_delivered >= 5 {
3655                                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3656                                         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3657                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3658                                         check_added_monitors!(nodes[0], 1);
3659
3660                                         if messages_delivered >= 6 {
3661                                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3662                                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3663                                                 check_added_monitors!(nodes[1], 1);
3664                                         }
3665                                 }
3666                         }
3667                 }
3668         }
3669
3670         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3671         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3672         if messages_delivered < 3 {
3673                 if simulate_broken_lnd {
3674                         // lnd has a long-standing bug where they send a funding_locked prior to a
3675                         // channel_reestablish if you reconnect prior to funding_locked time.
3676                         //
3677                         // Here we simulate that behavior, delivering a funding_locked immediately on
3678                         // reconnect. Note that we don't bother skipping the now-duplicate funding_locked sent
3679                         // in `reconnect_nodes` but we currently don't fail based on that.
3680                         //
3681                         // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3682                         nodes[1].node.handle_funding_locked(&nodes[0].node.get_our_node_id(), &as_funding_locked.as_ref().unwrap().0);
3683                 }
3684                 // Even if the funding_locked messages get exchanged, as long as nothing further was
3685                 // received on either side, both sides will need to resend them.
3686                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3687         } else if messages_delivered == 3 {
3688                 // nodes[0] still wants its RAA + commitment_signed
3689                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3690         } else if messages_delivered == 4 {
3691                 // nodes[0] still wants its commitment_signed
3692                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3693         } else if messages_delivered == 5 {
3694                 // nodes[1] still wants its final RAA
3695                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3696         } else if messages_delivered == 6 {
3697                 // Everything was delivered...
3698                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3699         }
3700
3701         let events_1 = nodes[1].node.get_and_clear_pending_events();
3702         assert_eq!(events_1.len(), 1);
3703         match events_1[0] {
3704                 Event::PendingHTLCsForwardable { .. } => { },
3705                 _ => panic!("Unexpected event"),
3706         };
3707
3708         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3709         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3710         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3711
3712         nodes[1].node.process_pending_htlc_forwards();
3713
3714         let events_2 = nodes[1].node.get_and_clear_pending_events();
3715         assert_eq!(events_2.len(), 1);
3716         match events_2[0] {
3717                 Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
3718                         assert_eq!(payment_hash_1, *payment_hash);
3719                         assert_eq!(amt, 1000000);
3720                         match &purpose {
3721                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3722                                         assert!(payment_preimage.is_none());
3723                                         assert_eq!(payment_secret_1, *payment_secret);
3724                                 },
3725                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
3726                         }
3727                 },
3728                 _ => panic!("Unexpected event"),
3729         }
3730
3731         nodes[1].node.claim_funds(payment_preimage_1);
3732         check_added_monitors!(nodes[1], 1);
3733
3734         let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3735         assert_eq!(events_3.len(), 1);
3736         let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3737                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3738                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3739                         assert!(updates.update_add_htlcs.is_empty());
3740                         assert!(updates.update_fail_htlcs.is_empty());
3741                         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3742                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3743                         assert!(updates.update_fee.is_none());
3744                         (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3745                 },
3746                 _ => panic!("Unexpected event"),
3747         };
3748
3749         if messages_delivered >= 1 {
3750                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3751
3752                 let events_4 = nodes[0].node.get_and_clear_pending_events();
3753                 assert_eq!(events_4.len(), 1);
3754                 match events_4[0] {
3755                         Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3756                                 assert_eq!(payment_preimage_1, *payment_preimage);
3757                                 assert_eq!(payment_hash_1, *payment_hash);
3758                         },
3759                         _ => panic!("Unexpected event"),
3760                 }
3761
3762                 if messages_delivered >= 2 {
3763                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3764                         check_added_monitors!(nodes[0], 1);
3765                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3766
3767                         if messages_delivered >= 3 {
3768                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3769                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3770                                 check_added_monitors!(nodes[1], 1);
3771
3772                                 if messages_delivered >= 4 {
3773                                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3774                                         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3775                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3776                                         check_added_monitors!(nodes[1], 1);
3777
3778                                         if messages_delivered >= 5 {
3779                                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3780                                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3781                                                 check_added_monitors!(nodes[0], 1);
3782                                         }
3783                                 }
3784                         }
3785                 }
3786         }
3787
3788         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3789         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3790         if messages_delivered < 2 {
3791                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3792                 if messages_delivered < 1 {
3793                         expect_payment_sent!(nodes[0], payment_preimage_1);
3794                 } else {
3795                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3796                 }
3797         } else if messages_delivered == 2 {
3798                 // nodes[0] still wants its RAA + commitment_signed
3799                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3800         } else if messages_delivered == 3 {
3801                 // nodes[0] still wants its commitment_signed
3802                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3803         } else if messages_delivered == 4 {
3804                 // nodes[1] still wants its final RAA
3805                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3806         } else if messages_delivered == 5 {
3807                 // Everything was delivered...
3808                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3809         }
3810
3811         if messages_delivered == 1 || messages_delivered == 2 {
3812                 expect_payment_path_successful!(nodes[0]);
3813         }
3814
3815         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3816         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3817         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3818
3819         if messages_delivered > 2 {
3820                 expect_payment_path_successful!(nodes[0]);
3821         }
3822
3823         // Channel should still work fine...
3824         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3825         let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3826         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3827 }
3828
3829 #[test]
3830 fn test_drop_messages_peer_disconnect_a() {
3831         do_test_drop_messages_peer_disconnect(0, true);
3832         do_test_drop_messages_peer_disconnect(0, false);
3833         do_test_drop_messages_peer_disconnect(1, false);
3834         do_test_drop_messages_peer_disconnect(2, false);
3835 }
3836
3837 #[test]
3838 fn test_drop_messages_peer_disconnect_b() {
3839         do_test_drop_messages_peer_disconnect(3, false);
3840         do_test_drop_messages_peer_disconnect(4, false);
3841         do_test_drop_messages_peer_disconnect(5, false);
3842         do_test_drop_messages_peer_disconnect(6, false);
3843 }
3844
3845 #[test]
3846 fn test_funding_peer_disconnect() {
3847         // Test that we can lock in our funding tx while disconnected
3848         let chanmon_cfgs = create_chanmon_cfgs(2);
3849         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3850         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3851         let persister: test_utils::TestPersister;
3852         let new_chain_monitor: test_utils::TestChainMonitor;
3853         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
3854         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3855         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3856
3857         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3858         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3859
3860         confirm_transaction(&nodes[0], &tx);
3861         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3862         assert!(events_1.is_empty());
3863
3864         reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3865
3866         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3867         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3868
3869         confirm_transaction(&nodes[1], &tx);
3870         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3871         assert!(events_2.is_empty());
3872
3873         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
3874         let as_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
3875         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
3876         let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
3877
3878         // nodes[0] hasn't yet received a funding_locked, so it only sends that on reconnect.
3879         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
3880         let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3881         assert_eq!(events_3.len(), 1);
3882         let as_funding_locked = match events_3[0] {
3883                 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3884                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3885                         msg.clone()
3886                 },
3887                 _ => panic!("Unexpected event {:?}", events_3[0]),
3888         };
3889
3890         // nodes[1] received nodes[0]'s funding_locked on the first reconnect above, so it should send
3891         // announcement_signatures as well as channel_update.
3892         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reestablish);
3893         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3894         assert_eq!(events_4.len(), 3);
3895         let chan_id;
3896         let bs_funding_locked = match events_4[0] {
3897                 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3898                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3899                         chan_id = msg.channel_id;
3900                         msg.clone()
3901                 },
3902                 _ => panic!("Unexpected event {:?}", events_4[0]),
3903         };
3904         let bs_announcement_sigs = match events_4[1] {
3905                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3906                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3907                         msg.clone()
3908                 },
3909                 _ => panic!("Unexpected event {:?}", events_4[1]),
3910         };
3911         match events_4[2] {
3912                 MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } => {
3913                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3914                 },
3915                 _ => panic!("Unexpected event {:?}", events_4[2]),
3916         }
3917
3918         // Re-deliver nodes[0]'s funding_locked, which nodes[1] can safely ignore. It currently
3919         // generates a duplicative private channel_update
3920         nodes[1].node.handle_funding_locked(&nodes[0].node.get_our_node_id(), &as_funding_locked);
3921         let events_5 = nodes[1].node.get_and_clear_pending_msg_events();
3922         assert_eq!(events_5.len(), 1);
3923         match events_5[0] {
3924                 MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } => {
3925                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3926                 },
3927                 _ => panic!("Unexpected event {:?}", events_5[0]),
3928         };
3929
3930         // When we deliver nodes[1]'s funding_locked, however, nodes[0] will generate its
3931         // announcement_signatures.
3932         nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &bs_funding_locked);
3933         let events_6 = nodes[0].node.get_and_clear_pending_msg_events();
3934         assert_eq!(events_6.len(), 1);
3935         let as_announcement_sigs = match events_6[0] {
3936                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3937                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3938                         msg.clone()
3939                 },
3940                 _ => panic!("Unexpected event {:?}", events_6[0]),
3941         };
3942
3943         // When we deliver nodes[1]'s announcement_signatures to nodes[0], nodes[0] should immediately
3944         // broadcast the channel announcement globally, as well as re-send its (now-public)
3945         // channel_update.
3946         nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3947         let events_7 = nodes[0].node.get_and_clear_pending_msg_events();
3948         assert_eq!(events_7.len(), 1);
3949         let (chan_announcement, as_update) = match events_7[0] {
3950                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3951                         (msg.clone(), update_msg.clone())
3952                 },
3953                 _ => panic!("Unexpected event {:?}", events_7[0]),
3954         };
3955
3956         // Finally, deliver nodes[0]'s announcement_signatures to nodes[1] and make sure it creates the
3957         // same channel_announcement.
3958         nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3959         let events_8 = nodes[1].node.get_and_clear_pending_msg_events();
3960         assert_eq!(events_8.len(), 1);
3961         let bs_update = match events_8[0] {
3962                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3963                         assert_eq!(*msg, chan_announcement);
3964                         update_msg.clone()
3965                 },
3966                 _ => panic!("Unexpected event {:?}", events_8[0]),
3967         };
3968
3969         // Provide the channel announcement and public updates to the network graph
3970         nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).unwrap();
3971         nodes[0].net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
3972         nodes[0].net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
3973
3974         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3975         let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3976         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
3977
3978         // Check that after deserialization and reconnection we can still generate an identical
3979         // channel_announcement from the cached signatures.
3980         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3981
3982         let nodes_0_serialized = nodes[0].node.encode();
3983         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
3984         get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
3985
3986         persister = test_utils::TestPersister::new();
3987         let keys_manager = &chanmon_cfgs[0].keys_manager;
3988         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);
3989         nodes[0].chain_monitor = &new_chain_monitor;
3990         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
3991         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
3992                 &mut chan_0_monitor_read, keys_manager).unwrap();
3993         assert!(chan_0_monitor_read.is_empty());
3994
3995         let mut nodes_0_read = &nodes_0_serialized[..];
3996         let (_, nodes_0_deserialized_tmp) = {
3997                 let mut channel_monitors = HashMap::new();
3998                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
3999                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4000                         default_config: UserConfig::default(),
4001                         keys_manager,
4002                         fee_estimator: node_cfgs[0].fee_estimator,
4003                         chain_monitor: nodes[0].chain_monitor,
4004                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4005                         logger: nodes[0].logger,
4006                         channel_monitors,
4007                 }).unwrap()
4008         };
4009         nodes_0_deserialized = nodes_0_deserialized_tmp;
4010         assert!(nodes_0_read.is_empty());
4011
4012         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4013         nodes[0].node = &nodes_0_deserialized;
4014         check_added_monitors!(nodes[0], 1);
4015
4016         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4017
4018         // The channel announcement should be re-generated exactly by broadcast_node_announcement.
4019         nodes[0].node.broadcast_node_announcement([0, 0, 0], [0; 32], Vec::new());
4020         let msgs = nodes[0].node.get_and_clear_pending_msg_events();
4021         let mut found_announcement = false;
4022         for event in msgs.iter() {
4023                 match event {
4024                         MessageSendEvent::BroadcastChannelAnnouncement { ref msg, .. } => {
4025                                 if *msg == chan_announcement { found_announcement = true; }
4026                         },
4027                         MessageSendEvent::BroadcastNodeAnnouncement { .. } => {},
4028                         _ => panic!("Unexpected event"),
4029                 }
4030         }
4031         assert!(found_announcement);
4032 }
4033
4034 #[test]
4035 fn test_funding_locked_without_best_block_updated() {
4036         // Previously, if we were offline when a funding transaction was locked in, and then we came
4037         // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
4038         // generate a funding_locked until a later best_block_updated. This tests that we generate the
4039         // funding_locked immediately instead.
4040         let chanmon_cfgs = create_chanmon_cfgs(2);
4041         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4042         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4043         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4044         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
4045
4046         let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
4047
4048         let conf_height = nodes[0].best_block_info().1 + 1;
4049         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
4050         let block_txn = [funding_tx];
4051         let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
4052         let conf_block_header = nodes[0].get_block_header(conf_height);
4053         nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
4054
4055         // Ensure nodes[0] generates a funding_locked after the transactions_confirmed
4056         let as_funding_locked = get_event_msg!(nodes[0], MessageSendEvent::SendFundingLocked, nodes[1].node.get_our_node_id());
4057         nodes[1].node.handle_funding_locked(&nodes[0].node.get_our_node_id(), &as_funding_locked);
4058 }
4059
4060 #[test]
4061 fn test_drop_messages_peer_disconnect_dual_htlc() {
4062         // Test that we can handle reconnecting when both sides of a channel have pending
4063         // commitment_updates when we disconnect.
4064         let chanmon_cfgs = create_chanmon_cfgs(2);
4065         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4066         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4067         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4068         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4069
4070         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4071
4072         // Now try to send a second payment which will fail to send
4073         let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
4074         nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
4075         check_added_monitors!(nodes[0], 1);
4076
4077         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
4078         assert_eq!(events_1.len(), 1);
4079         match events_1[0] {
4080                 MessageSendEvent::UpdateHTLCs { .. } => {},
4081                 _ => panic!("Unexpected event"),
4082         }
4083
4084         assert!(nodes[1].node.claim_funds(payment_preimage_1));
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: InitFeatures::empty(), remote_network_address: None });
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: InitFeatures::empty(), remote_network_address: None });
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, InitFeatures::known(), InitFeatures::known());
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                 nodes[0].node.send_payment_along_path(&route.paths[0], &route.payment_params, &our_payment_hash, &Some(payment_secret), 200000, cur_height, payment_id, &None).unwrap();
4226                 check_added_monitors!(nodes[0], 1);
4227                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4228                 assert_eq!(events.len(), 1);
4229                 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4230                 // hop should *not* yet generate any PaymentReceived event(s).
4231                 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4232                 our_payment_hash
4233         } else {
4234                 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4235         };
4236
4237         let mut block = Block {
4238                 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
4239                 txdata: vec![],
4240         };
4241         connect_block(&nodes[0], &block);
4242         connect_block(&nodes[1], &block);
4243         let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4244         for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4245                 block.header.prev_blockhash = block.block_hash();
4246                 connect_block(&nodes[0], &block);
4247                 connect_block(&nodes[1], &block);
4248         }
4249
4250         expect_pending_htlcs_forwardable!(nodes[1]);
4251
4252         check_added_monitors!(nodes[1], 1);
4253         let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4254         assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4255         assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4256         assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4257         assert!(htlc_timeout_updates.update_fee.is_none());
4258
4259         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4260         commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4261         // 100_000 msat as u64, followed by the height at which we failed back above
4262         let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
4263         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(block_count - 1));
4264         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4265 }
4266
4267 #[test]
4268 fn test_htlc_timeout() {
4269         do_test_htlc_timeout(true);
4270         do_test_htlc_timeout(false);
4271 }
4272
4273 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4274         // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4275         let chanmon_cfgs = create_chanmon_cfgs(3);
4276         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4277         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4278         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4279         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4280         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4281
4282         // Make sure all nodes are at the same starting height
4283         connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4284         connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4285         connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4286
4287         // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4288         let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4289         {
4290                 nodes[1].node.send_payment(&route, first_payment_hash, &Some(first_payment_secret)).unwrap();
4291         }
4292         assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4293         check_added_monitors!(nodes[1], 1);
4294
4295         // Now attempt to route a second payment, which should be placed in the holding cell
4296         let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4297         let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4298         sending_node.node.send_payment(&route, second_payment_hash, &Some(second_payment_secret)).unwrap();
4299         if forwarded_htlc {
4300                 check_added_monitors!(nodes[0], 1);
4301                 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4302                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4303                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4304                 expect_pending_htlcs_forwardable!(nodes[1]);
4305         }
4306         check_added_monitors!(nodes[1], 0);
4307
4308         connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4309         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4310         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4311         connect_blocks(&nodes[1], 1);
4312
4313         if forwarded_htlc {
4314                 expect_pending_htlcs_forwardable!(nodes[1]);
4315                 check_added_monitors!(nodes[1], 1);
4316                 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4317                 assert_eq!(fail_commit.len(), 1);
4318                 match fail_commit[0] {
4319                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4320                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4321                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4322                         },
4323                         _ => unreachable!(),
4324                 }
4325                 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4326         } else {
4327                 let events = nodes[1].node.get_and_clear_pending_events();
4328                 assert_eq!(events.len(), 2);
4329                 if let Event::PaymentPathFailed { ref payment_hash, .. } = events[0] {
4330                         assert_eq!(*payment_hash, second_payment_hash);
4331                 } else { panic!("Unexpected event"); }
4332                 if let Event::PaymentFailed { ref payment_hash, .. } = events[1] {
4333                         assert_eq!(*payment_hash, second_payment_hash);
4334                 } else { panic!("Unexpected event"); }
4335         }
4336 }
4337
4338 #[test]
4339 fn test_holding_cell_htlc_add_timeouts() {
4340         do_test_holding_cell_htlc_add_timeouts(false);
4341         do_test_holding_cell_htlc_add_timeouts(true);
4342 }
4343
4344 #[test]
4345 fn test_no_txn_manager_serialize_deserialize() {
4346         let chanmon_cfgs = create_chanmon_cfgs(2);
4347         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4348         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4349         let logger: test_utils::TestLogger;
4350         let fee_estimator: test_utils::TestFeeEstimator;
4351         let persister: test_utils::TestPersister;
4352         let new_chain_monitor: test_utils::TestChainMonitor;
4353         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4354         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4355
4356         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
4357
4358         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4359
4360         let nodes_0_serialized = nodes[0].node.encode();
4361         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4362         get_monitor!(nodes[0], OutPoint { txid: tx.txid(), index: 0 }.to_channel_id())
4363                 .write(&mut chan_0_monitor_serialized).unwrap();
4364
4365         logger = test_utils::TestLogger::new();
4366         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4367         persister = test_utils::TestPersister::new();
4368         let keys_manager = &chanmon_cfgs[0].keys_manager;
4369         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4370         nodes[0].chain_monitor = &new_chain_monitor;
4371         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4372         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4373                 &mut chan_0_monitor_read, keys_manager).unwrap();
4374         assert!(chan_0_monitor_read.is_empty());
4375
4376         let mut nodes_0_read = &nodes_0_serialized[..];
4377         let config = UserConfig::default();
4378         let (_, nodes_0_deserialized_tmp) = {
4379                 let mut channel_monitors = HashMap::new();
4380                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4381                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4382                         default_config: config,
4383                         keys_manager,
4384                         fee_estimator: &fee_estimator,
4385                         chain_monitor: nodes[0].chain_monitor,
4386                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4387                         logger: &logger,
4388                         channel_monitors,
4389                 }).unwrap()
4390         };
4391         nodes_0_deserialized = nodes_0_deserialized_tmp;
4392         assert!(nodes_0_read.is_empty());
4393
4394         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4395         nodes[0].node = &nodes_0_deserialized;
4396         assert_eq!(nodes[0].node.list_channels().len(), 1);
4397         check_added_monitors!(nodes[0], 1);
4398
4399         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4400         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4401         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4402         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4403
4404         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4405         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4406         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4407         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4408
4409         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4410         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4411         for node in nodes.iter() {
4412                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4413                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4414                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4415         }
4416
4417         send_payment(&nodes[0], &[&nodes[1]], 1000000);
4418 }
4419
4420 #[test]
4421 fn test_manager_serialize_deserialize_events() {
4422         // This test makes sure the events field in ChannelManager survives de/serialization
4423         let chanmon_cfgs = create_chanmon_cfgs(2);
4424         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4425         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4426         let fee_estimator: test_utils::TestFeeEstimator;
4427         let persister: test_utils::TestPersister;
4428         let logger: test_utils::TestLogger;
4429         let new_chain_monitor: test_utils::TestChainMonitor;
4430         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4431         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4432
4433         // Start creating a channel, but stop right before broadcasting the funding transaction
4434         let channel_value = 100000;
4435         let push_msat = 10001;
4436         let a_flags = InitFeatures::known();
4437         let b_flags = InitFeatures::known();
4438         let node_a = nodes.remove(0);
4439         let node_b = nodes.remove(0);
4440         node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
4441         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()));
4442         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()));
4443
4444         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, channel_value, 42);
4445
4446         node_a.node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
4447         check_added_monitors!(node_a, 0);
4448
4449         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()));
4450         {
4451                 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
4452                 assert_eq!(added_monitors.len(), 1);
4453                 assert_eq!(added_monitors[0].0, funding_output);
4454                 added_monitors.clear();
4455         }
4456
4457         let bs_funding_signed = get_event_msg!(node_b, MessageSendEvent::SendFundingSigned, node_a.node.get_our_node_id());
4458         node_a.node.handle_funding_signed(&node_b.node.get_our_node_id(), &bs_funding_signed);
4459         {
4460                 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
4461                 assert_eq!(added_monitors.len(), 1);
4462                 assert_eq!(added_monitors[0].0, funding_output);
4463                 added_monitors.clear();
4464         }
4465         // Normally, this is where node_a would broadcast the funding transaction, but the test de/serializes first instead
4466
4467         nodes.push(node_a);
4468         nodes.push(node_b);
4469
4470         // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4471         let nodes_0_serialized = nodes[0].node.encode();
4472         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4473         get_monitor!(nodes[0], bs_funding_signed.channel_id).write(&mut chan_0_monitor_serialized).unwrap();
4474
4475         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4476         logger = test_utils::TestLogger::new();
4477         persister = test_utils::TestPersister::new();
4478         let keys_manager = &chanmon_cfgs[0].keys_manager;
4479         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4480         nodes[0].chain_monitor = &new_chain_monitor;
4481         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4482         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4483                 &mut chan_0_monitor_read, keys_manager).unwrap();
4484         assert!(chan_0_monitor_read.is_empty());
4485
4486         let mut nodes_0_read = &nodes_0_serialized[..];
4487         let config = UserConfig::default();
4488         let (_, nodes_0_deserialized_tmp) = {
4489                 let mut channel_monitors = HashMap::new();
4490                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4491                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4492                         default_config: config,
4493                         keys_manager,
4494                         fee_estimator: &fee_estimator,
4495                         chain_monitor: nodes[0].chain_monitor,
4496                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4497                         logger: &logger,
4498                         channel_monitors,
4499                 }).unwrap()
4500         };
4501         nodes_0_deserialized = nodes_0_deserialized_tmp;
4502         assert!(nodes_0_read.is_empty());
4503
4504         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4505
4506         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4507         nodes[0].node = &nodes_0_deserialized;
4508
4509         // After deserializing, make sure the funding_transaction is still held by the channel manager
4510         let events_4 = nodes[0].node.get_and_clear_pending_events();
4511         assert_eq!(events_4.len(), 0);
4512         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
4513         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
4514
4515         // Make sure the channel is functioning as though the de/serialization never happened
4516         assert_eq!(nodes[0].node.list_channels().len(), 1);
4517         check_added_monitors!(nodes[0], 1);
4518
4519         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4520         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4521         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4522         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4523
4524         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4525         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4526         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4527         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4528
4529         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4530         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4531         for node in nodes.iter() {
4532                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4533                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4534                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4535         }
4536
4537         send_payment(&nodes[0], &[&nodes[1]], 1000000);
4538 }
4539
4540 #[test]
4541 fn test_simple_manager_serialize_deserialize() {
4542         let chanmon_cfgs = create_chanmon_cfgs(2);
4543         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4544         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4545         let logger: test_utils::TestLogger;
4546         let fee_estimator: test_utils::TestFeeEstimator;
4547         let persister: test_utils::TestPersister;
4548         let new_chain_monitor: test_utils::TestChainMonitor;
4549         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4550         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4551         let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
4552
4553         let (our_payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4554         let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4555
4556         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4557
4558         let nodes_0_serialized = nodes[0].node.encode();
4559         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4560         get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
4561
4562         logger = test_utils::TestLogger::new();
4563         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4564         persister = test_utils::TestPersister::new();
4565         let keys_manager = &chanmon_cfgs[0].keys_manager;
4566         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4567         nodes[0].chain_monitor = &new_chain_monitor;
4568         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4569         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4570                 &mut chan_0_monitor_read, keys_manager).unwrap();
4571         assert!(chan_0_monitor_read.is_empty());
4572
4573         let mut nodes_0_read = &nodes_0_serialized[..];
4574         let (_, nodes_0_deserialized_tmp) = {
4575                 let mut channel_monitors = HashMap::new();
4576                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4577                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4578                         default_config: UserConfig::default(),
4579                         keys_manager,
4580                         fee_estimator: &fee_estimator,
4581                         chain_monitor: nodes[0].chain_monitor,
4582                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4583                         logger: &logger,
4584                         channel_monitors,
4585                 }).unwrap()
4586         };
4587         nodes_0_deserialized = nodes_0_deserialized_tmp;
4588         assert!(nodes_0_read.is_empty());
4589
4590         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4591         nodes[0].node = &nodes_0_deserialized;
4592         check_added_monitors!(nodes[0], 1);
4593
4594         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4595
4596         fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4597         claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
4598 }
4599
4600 #[test]
4601 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4602         // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4603         let chanmon_cfgs = create_chanmon_cfgs(4);
4604         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4605         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4606         let logger: test_utils::TestLogger;
4607         let fee_estimator: test_utils::TestFeeEstimator;
4608         let persister: test_utils::TestPersister;
4609         let new_chain_monitor: test_utils::TestChainMonitor;
4610         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4611         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4612         let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
4613         let chan_id_2 = create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known()).2;
4614         let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
4615
4616         let mut node_0_stale_monitors_serialized = Vec::new();
4617         for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4618                 let mut writer = test_utils::TestVecWriter(Vec::new());
4619                 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4620                 node_0_stale_monitors_serialized.push(writer.0);
4621         }
4622
4623         let (our_payment_preimage, _, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4624
4625         // Serialize the ChannelManager here, but the monitor we keep up-to-date
4626         let nodes_0_serialized = nodes[0].node.encode();
4627
4628         route_payment(&nodes[0], &[&nodes[3]], 1000000);
4629         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4630         nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4631         nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4632
4633         // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4634         // nodes[3])
4635         let mut node_0_monitors_serialized = Vec::new();
4636         for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4637                 let mut writer = test_utils::TestVecWriter(Vec::new());
4638                 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4639                 node_0_monitors_serialized.push(writer.0);
4640         }
4641
4642         logger = test_utils::TestLogger::new();
4643         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4644         persister = test_utils::TestPersister::new();
4645         let keys_manager = &chanmon_cfgs[0].keys_manager;
4646         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4647         nodes[0].chain_monitor = &new_chain_monitor;
4648
4649
4650         let mut node_0_stale_monitors = Vec::new();
4651         for serialized in node_0_stale_monitors_serialized.iter() {
4652                 let mut read = &serialized[..];
4653                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4654                 assert!(read.is_empty());
4655                 node_0_stale_monitors.push(monitor);
4656         }
4657
4658         let mut node_0_monitors = Vec::new();
4659         for serialized in node_0_monitors_serialized.iter() {
4660                 let mut read = &serialized[..];
4661                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4662                 assert!(read.is_empty());
4663                 node_0_monitors.push(monitor);
4664         }
4665
4666         let mut nodes_0_read = &nodes_0_serialized[..];
4667         if let Err(msgs::DecodeError::InvalidValue) =
4668                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4669                 default_config: UserConfig::default(),
4670                 keys_manager,
4671                 fee_estimator: &fee_estimator,
4672                 chain_monitor: nodes[0].chain_monitor,
4673                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4674                 logger: &logger,
4675                 channel_monitors: node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4676         }) { } else {
4677                 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4678         };
4679
4680         let mut nodes_0_read = &nodes_0_serialized[..];
4681         let (_, nodes_0_deserialized_tmp) =
4682                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4683                 default_config: UserConfig::default(),
4684                 keys_manager,
4685                 fee_estimator: &fee_estimator,
4686                 chain_monitor: nodes[0].chain_monitor,
4687                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4688                 logger: &logger,
4689                 channel_monitors: node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4690         }).unwrap();
4691         nodes_0_deserialized = nodes_0_deserialized_tmp;
4692         assert!(nodes_0_read.is_empty());
4693
4694         { // Channel close should result in a commitment tx
4695                 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4696                 assert_eq!(txn.len(), 1);
4697                 check_spends!(txn[0], funding_tx);
4698                 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4699         }
4700
4701         for monitor in node_0_monitors.drain(..) {
4702                 assert!(nodes[0].chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor).is_ok());
4703                 check_added_monitors!(nodes[0], 1);
4704         }
4705         nodes[0].node = &nodes_0_deserialized;
4706         check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
4707
4708         // nodes[1] and nodes[2] have no lost state with nodes[0]...
4709         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4710         reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4711         //... and we can even still claim the payment!
4712         claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage);
4713
4714         nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4715         let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4716         nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4717         nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4718         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4719         assert_eq!(msg_events.len(), 1);
4720         if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
4721                 match action {
4722                         &ErrorAction::SendErrorMessage { ref msg } => {
4723                                 assert_eq!(msg.channel_id, channel_id);
4724                         },
4725                         _ => panic!("Unexpected event!"),
4726                 }
4727         }
4728 }
4729
4730 macro_rules! check_spendable_outputs {
4731         ($node: expr, $keysinterface: expr) => {
4732                 {
4733                         let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4734                         let mut txn = Vec::new();
4735                         let mut all_outputs = Vec::new();
4736                         let secp_ctx = Secp256k1::new();
4737                         for event in events.drain(..) {
4738                                 match event {
4739                                         Event::SpendableOutputs { mut outputs } => {
4740                                                 for outp in outputs.drain(..) {
4741                                                         txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4742                                                         all_outputs.push(outp);
4743                                                 }
4744                                         },
4745                                         _ => panic!("Unexpected event"),
4746                                 };
4747                         }
4748                         if all_outputs.len() > 1 {
4749                                 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) {
4750                                         txn.push(tx);
4751                                 }
4752                         }
4753                         txn
4754                 }
4755         }
4756 }
4757
4758 #[test]
4759 fn test_claim_sizeable_push_msat() {
4760         // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4761         let chanmon_cfgs = create_chanmon_cfgs(2);
4762         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4763         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4764         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4765
4766         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000, InitFeatures::known(), InitFeatures::known());
4767         nodes[1].node.force_close_channel(&chan.2).unwrap();
4768         check_closed_broadcast!(nodes[1], true);
4769         check_added_monitors!(nodes[1], 1);
4770         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4771         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4772         assert_eq!(node_txn.len(), 1);
4773         check_spends!(node_txn[0], chan.3);
4774         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
4775
4776         mine_transaction(&nodes[1], &node_txn[0]);
4777         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4778
4779         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4780         assert_eq!(spend_txn.len(), 1);
4781         assert_eq!(spend_txn[0].input.len(), 1);
4782         check_spends!(spend_txn[0], node_txn[0]);
4783         assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
4784 }
4785
4786 #[test]
4787 fn test_claim_on_remote_sizeable_push_msat() {
4788         // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4789         // to_remote output is encumbered by a P2WPKH
4790         let chanmon_cfgs = create_chanmon_cfgs(2);
4791         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4792         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4793         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4794
4795         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000, InitFeatures::known(), InitFeatures::known());
4796         nodes[0].node.force_close_channel(&chan.2).unwrap();
4797         check_closed_broadcast!(nodes[0], true);
4798         check_added_monitors!(nodes[0], 1);
4799         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4800
4801         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4802         assert_eq!(node_txn.len(), 1);
4803         check_spends!(node_txn[0], chan.3);
4804         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
4805
4806         mine_transaction(&nodes[1], &node_txn[0]);
4807         check_closed_broadcast!(nodes[1], true);
4808         check_added_monitors!(nodes[1], 1);
4809         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4810         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4811
4812         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4813         assert_eq!(spend_txn.len(), 1);
4814         check_spends!(spend_txn[0], node_txn[0]);
4815 }
4816
4817 #[test]
4818 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4819         // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4820         // to_remote output is encumbered by a P2WPKH
4821
4822         let chanmon_cfgs = create_chanmon_cfgs(2);
4823         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4824         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4825         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4826
4827         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::known(), InitFeatures::known());
4828         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4829         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4830         assert_eq!(revoked_local_txn[0].input.len(), 1);
4831         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4832
4833         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4834         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4835         check_closed_broadcast!(nodes[1], true);
4836         check_added_monitors!(nodes[1], 1);
4837         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4838
4839         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4840         mine_transaction(&nodes[1], &node_txn[0]);
4841         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4842
4843         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4844         assert_eq!(spend_txn.len(), 3);
4845         check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4846         check_spends!(spend_txn[1], node_txn[0]);
4847         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4848 }
4849
4850 #[test]
4851 fn test_static_spendable_outputs_preimage_tx() {
4852         let chanmon_cfgs = create_chanmon_cfgs(2);
4853         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4854         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4855         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4856
4857         // Create some initial channels
4858         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4859
4860         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4861
4862         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4863         assert_eq!(commitment_tx[0].input.len(), 1);
4864         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4865
4866         // Settle A's commitment tx on B's chain
4867         assert!(nodes[1].node.claim_funds(payment_preimage));
4868         check_added_monitors!(nodes[1], 1);
4869         mine_transaction(&nodes[1], &commitment_tx[0]);
4870         check_added_monitors!(nodes[1], 1);
4871         let events = nodes[1].node.get_and_clear_pending_msg_events();
4872         match events[0] {
4873                 MessageSendEvent::UpdateHTLCs { .. } => {},
4874                 _ => panic!("Unexpected event"),
4875         }
4876         match events[1] {
4877                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4878                 _ => panic!("Unexepected event"),
4879         }
4880
4881         // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4882         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4883         assert_eq!(node_txn.len(), 3);
4884         check_spends!(node_txn[0], commitment_tx[0]);
4885         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4886         check_spends!(node_txn[1], chan_1.3);
4887         check_spends!(node_txn[2], node_txn[1]);
4888
4889         mine_transaction(&nodes[1], &node_txn[0]);
4890         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4891         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4892
4893         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4894         assert_eq!(spend_txn.len(), 1);
4895         check_spends!(spend_txn[0], node_txn[0]);
4896 }
4897
4898 #[test]
4899 fn test_static_spendable_outputs_timeout_tx() {
4900         let chanmon_cfgs = create_chanmon_cfgs(2);
4901         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4902         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4903         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4904
4905         // Create some initial channels
4906         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4907
4908         // Rebalance the network a bit by relaying one payment through all the channels ...
4909         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4910
4911         let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4912
4913         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4914         assert_eq!(commitment_tx[0].input.len(), 1);
4915         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4916
4917         // Settle A's commitment tx on B' chain
4918         mine_transaction(&nodes[1], &commitment_tx[0]);
4919         check_added_monitors!(nodes[1], 1);
4920         let events = nodes[1].node.get_and_clear_pending_msg_events();
4921         match events[0] {
4922                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4923                 _ => panic!("Unexpected event"),
4924         }
4925         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4926
4927         // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4928         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4929         assert_eq!(node_txn.len(), 2); // ChannelManager : 1 local commitent tx, ChannelMonitor: timeout tx
4930         check_spends!(node_txn[0], chan_1.3.clone());
4931         check_spends!(node_txn[1],  commitment_tx[0].clone());
4932         assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4933
4934         mine_transaction(&nodes[1], &node_txn[1]);
4935         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4936         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4937         expect_payment_failed!(nodes[1], our_payment_hash, true);
4938
4939         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4940         assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4941         check_spends!(spend_txn[0], commitment_tx[0]);
4942         check_spends!(spend_txn[1], node_txn[1]);
4943         check_spends!(spend_txn[2], node_txn[1], commitment_tx[0]); // All outputs
4944 }
4945
4946 #[test]
4947 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4948         let chanmon_cfgs = create_chanmon_cfgs(2);
4949         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4950         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4951         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4952
4953         // Create some initial channels
4954         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4955
4956         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4957         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4958         assert_eq!(revoked_local_txn[0].input.len(), 1);
4959         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4960
4961         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4962
4963         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4964         check_closed_broadcast!(nodes[1], true);
4965         check_added_monitors!(nodes[1], 1);
4966         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4967
4968         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4969         assert_eq!(node_txn.len(), 2);
4970         assert_eq!(node_txn[0].input.len(), 2);
4971         check_spends!(node_txn[0], revoked_local_txn[0]);
4972
4973         mine_transaction(&nodes[1], &node_txn[0]);
4974         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4975
4976         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4977         assert_eq!(spend_txn.len(), 1);
4978         check_spends!(spend_txn[0], node_txn[0]);
4979 }
4980
4981 #[test]
4982 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4983         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4984         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4985         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4986         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4987         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4988
4989         // Create some initial channels
4990         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4991
4992         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4993         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4994         assert_eq!(revoked_local_txn[0].input.len(), 1);
4995         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4996
4997         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4998
4999         // A will generate HTLC-Timeout from revoked commitment tx
5000         mine_transaction(&nodes[0], &revoked_local_txn[0]);
5001         check_closed_broadcast!(nodes[0], true);
5002         check_added_monitors!(nodes[0], 1);
5003         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5004         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5005
5006         let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5007         assert_eq!(revoked_htlc_txn.len(), 2);
5008         check_spends!(revoked_htlc_txn[0], chan_1.3);
5009         assert_eq!(revoked_htlc_txn[1].input.len(), 1);
5010         assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5011         check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
5012         assert_ne!(revoked_htlc_txn[1].lock_time, 0); // HTLC-Timeout
5013
5014         // B will generate justice tx from A's revoked commitment/HTLC tx
5015         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5016         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[1].clone()] });
5017         check_closed_broadcast!(nodes[1], true);
5018         check_added_monitors!(nodes[1], 1);
5019         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5020
5021         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5022         assert_eq!(node_txn.len(), 3); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs, ChannelManager: local commitment tx
5023         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5024         // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
5025         // transactions next...
5026         assert_eq!(node_txn[0].input.len(), 3);
5027         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[1]);
5028
5029         assert_eq!(node_txn[1].input.len(), 2);
5030         check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[1]);
5031         if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[1].txid() {
5032                 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
5033         } else {
5034                 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[1].txid());
5035                 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[1].input[0].previous_output);
5036         }
5037
5038         assert_eq!(node_txn[2].input.len(), 1);
5039         check_spends!(node_txn[2], chan_1.3);
5040
5041         mine_transaction(&nodes[1], &node_txn[1]);
5042         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5043
5044         // Check B's ChannelMonitor was able to generate the right spendable output descriptor
5045         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5046         assert_eq!(spend_txn.len(), 1);
5047         assert_eq!(spend_txn[0].input.len(), 1);
5048         check_spends!(spend_txn[0], node_txn[1]);
5049 }
5050
5051 #[test]
5052 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
5053         let mut chanmon_cfgs = create_chanmon_cfgs(2);
5054         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
5055         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5056         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5057         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5058
5059         // Create some initial channels
5060         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5061
5062         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5063         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5064         assert_eq!(revoked_local_txn[0].input.len(), 1);
5065         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5066
5067         // The to-be-revoked commitment tx should have one HTLC and one to_remote output
5068         assert_eq!(revoked_local_txn[0].output.len(), 2);
5069
5070         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
5071
5072         // B will generate HTLC-Success from revoked commitment tx
5073         mine_transaction(&nodes[1], &revoked_local_txn[0]);
5074         check_closed_broadcast!(nodes[1], true);
5075         check_added_monitors!(nodes[1], 1);
5076         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5077         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5078
5079         assert_eq!(revoked_htlc_txn.len(), 2);
5080         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
5081         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5082         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
5083
5084         // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
5085         let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
5086         assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
5087
5088         // A will generate justice tx from B's revoked commitment/HTLC tx
5089         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5090         connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
5091         check_closed_broadcast!(nodes[0], true);
5092         check_added_monitors!(nodes[0], 1);
5093         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5094
5095         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5096         assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
5097
5098         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5099         // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
5100         // transactions next...
5101         assert_eq!(node_txn[0].input.len(), 2);
5102         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
5103         if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
5104                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5105         } else {
5106                 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
5107                 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5108         }
5109
5110         assert_eq!(node_txn[1].input.len(), 1);
5111         check_spends!(node_txn[1], revoked_htlc_txn[0]);
5112
5113         check_spends!(node_txn[2], chan_1.3);
5114
5115         mine_transaction(&nodes[0], &node_txn[1]);
5116         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5117
5118         // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
5119         // didn't try to generate any new transactions.
5120
5121         // Check A's ChannelMonitor was able to generate the right spendable output descriptor
5122         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5123         assert_eq!(spend_txn.len(), 3);
5124         assert_eq!(spend_txn[0].input.len(), 1);
5125         check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
5126         assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5127         check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
5128         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
5129 }
5130
5131 #[test]
5132 fn test_onchain_to_onchain_claim() {
5133         // Test that in case of channel closure, we detect the state of output and claim HTLC
5134         // on downstream peer's remote commitment tx.
5135         // First, have C claim an HTLC against its own latest commitment transaction.
5136         // Then, broadcast these to B, which should update the monitor downstream on the A<->B
5137         // channel.
5138         // Finally, check that B will claim the HTLC output if A's latest commitment transaction
5139         // gets broadcast.
5140
5141         let chanmon_cfgs = create_chanmon_cfgs(3);
5142         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5143         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5144         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5145
5146         // Create some initial channels
5147         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5148         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5149
5150         // Ensure all nodes are at the same height
5151         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5152         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5153         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5154         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5155
5156         // Rebalance the network a bit by relaying one payment through all the channels ...
5157         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5158         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5159
5160         let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
5161         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
5162         check_spends!(commitment_tx[0], chan_2.3);
5163         nodes[2].node.claim_funds(payment_preimage);
5164         check_added_monitors!(nodes[2], 1);
5165         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5166         assert!(updates.update_add_htlcs.is_empty());
5167         assert!(updates.update_fail_htlcs.is_empty());
5168         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5169         assert!(updates.update_fail_malformed_htlcs.is_empty());
5170
5171         mine_transaction(&nodes[2], &commitment_tx[0]);
5172         check_closed_broadcast!(nodes[2], true);
5173         check_added_monitors!(nodes[2], 1);
5174         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5175
5176         let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
5177         assert_eq!(c_txn.len(), 3);
5178         assert_eq!(c_txn[0], c_txn[2]);
5179         assert_eq!(commitment_tx[0], c_txn[1]);
5180         check_spends!(c_txn[1], chan_2.3);
5181         check_spends!(c_txn[2], c_txn[1]);
5182         assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
5183         assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5184         assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5185         assert_eq!(c_txn[0].lock_time, 0); // Success tx
5186
5187         // 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
5188         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
5189         connect_block(&nodes[1], &Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]});
5190         check_added_monitors!(nodes[1], 1);
5191         let events = nodes[1].node.get_and_clear_pending_events();
5192         assert_eq!(events.len(), 2);
5193         match events[0] {
5194                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5195                 _ => panic!("Unexpected event"),
5196         }
5197         match events[1] {
5198                 Event::PaymentForwarded { fee_earned_msat, source_channel_id, claim_from_onchain_tx } => {
5199                         assert_eq!(fee_earned_msat, Some(1000));
5200                         assert_eq!(source_channel_id, Some(chan_1.2));
5201                         assert_eq!(claim_from_onchain_tx, true);
5202                 },
5203                 _ => panic!("Unexpected event"),
5204         }
5205         {
5206                 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5207                 // ChannelMonitor: claim tx
5208                 assert_eq!(b_txn.len(), 1);
5209                 check_spends!(b_txn[0], chan_2.3); // B local commitment tx, issued by ChannelManager
5210                 b_txn.clear();
5211         }
5212         check_added_monitors!(nodes[1], 1);
5213         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5214         assert_eq!(msg_events.len(), 3);
5215         match msg_events[0] {
5216                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5217                 _ => panic!("Unexpected event"),
5218         }
5219         match msg_events[1] {
5220                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
5221                 _ => panic!("Unexpected event"),
5222         }
5223         match msg_events[2] {
5224                 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, .. } } => {
5225                         assert!(update_add_htlcs.is_empty());
5226                         assert!(update_fail_htlcs.is_empty());
5227                         assert_eq!(update_fulfill_htlcs.len(), 1);
5228                         assert!(update_fail_malformed_htlcs.is_empty());
5229                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5230                 },
5231                 _ => panic!("Unexpected event"),
5232         };
5233         // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
5234         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5235         mine_transaction(&nodes[1], &commitment_tx[0]);
5236         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5237         let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5238         // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
5239         assert_eq!(b_txn.len(), 3);
5240         check_spends!(b_txn[1], chan_1.3);
5241         check_spends!(b_txn[2], b_txn[1]);
5242         check_spends!(b_txn[0], commitment_tx[0]);
5243         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5244         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5245         assert_eq!(b_txn[0].lock_time, 0); // Success tx
5246
5247         check_closed_broadcast!(nodes[1], true);
5248         check_added_monitors!(nodes[1], 1);
5249 }
5250
5251 #[test]
5252 fn test_duplicate_payment_hash_one_failure_one_success() {
5253         // Topology : A --> B --> C --> D
5254         // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5255         // Note that because C will refuse to generate two payment secrets for the same payment hash,
5256         // we forward one of the payments onwards to D.
5257         let chanmon_cfgs = create_chanmon_cfgs(4);
5258         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
5259         // When this test was written, the default base fee floated based on the HTLC count.
5260         // It is now fixed, so we simply set the fee to the expected value here.
5261         let mut config = test_default_channel_config();
5262         config.channel_options.forwarding_fee_base_msat = 196;
5263         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
5264                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5265         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
5266
5267         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5268         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5269         create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5270
5271         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5272         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5273         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5274         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5275         connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
5276
5277         let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
5278
5279         let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200).unwrap();
5280         // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
5281         // script push size limit so that the below script length checks match
5282         // ACCEPTED_HTLC_SCRIPT_WEIGHT.
5283         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id())
5284                 .with_features(InvoiceFeatures::known());
5285         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 900000, TEST_FINAL_CLTV - 40);
5286         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 900000, duplicate_payment_hash, payment_secret);
5287
5288         let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5289         assert_eq!(commitment_txn[0].input.len(), 1);
5290         check_spends!(commitment_txn[0], chan_2.3);
5291
5292         mine_transaction(&nodes[1], &commitment_txn[0]);
5293         check_closed_broadcast!(nodes[1], true);
5294         check_added_monitors!(nodes[1], 1);
5295         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5296         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
5297
5298         let htlc_timeout_tx;
5299         { // Extract one of the two HTLC-Timeout transaction
5300                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5301                 // ChannelMonitor: timeout tx * 2-or-3, ChannelManager: local commitment tx
5302                 assert!(node_txn.len() == 4 || node_txn.len() == 3);
5303                 check_spends!(node_txn[0], chan_2.3);
5304
5305                 check_spends!(node_txn[1], commitment_txn[0]);
5306                 assert_eq!(node_txn[1].input.len(), 1);
5307
5308                 if node_txn.len() > 3 {
5309                         check_spends!(node_txn[2], commitment_txn[0]);
5310                         assert_eq!(node_txn[2].input.len(), 1);
5311                         assert_eq!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
5312
5313                         check_spends!(node_txn[3], commitment_txn[0]);
5314                         assert_ne!(node_txn[1].input[0].previous_output, node_txn[3].input[0].previous_output);
5315                 } else {
5316                         check_spends!(node_txn[2], commitment_txn[0]);
5317                         assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
5318                 }
5319
5320                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5321                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5322                 if node_txn.len() > 3 {
5323                         assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5324                 }
5325                 htlc_timeout_tx = node_txn[1].clone();
5326         }
5327
5328         nodes[2].node.claim_funds(our_payment_preimage);
5329         mine_transaction(&nodes[2], &commitment_txn[0]);
5330         check_added_monitors!(nodes[2], 2);
5331         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5332         let events = nodes[2].node.get_and_clear_pending_msg_events();
5333         match events[0] {
5334                 MessageSendEvent::UpdateHTLCs { .. } => {},
5335                 _ => panic!("Unexpected event"),
5336         }
5337         match events[1] {
5338                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5339                 _ => panic!("Unexepected event"),
5340         }
5341         let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5342         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)
5343         check_spends!(htlc_success_txn[0], commitment_txn[0]);
5344         check_spends!(htlc_success_txn[1], commitment_txn[0]);
5345         assert_eq!(htlc_success_txn[0].input.len(), 1);
5346         assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5347         assert_eq!(htlc_success_txn[1].input.len(), 1);
5348         assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5349         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
5350         assert_eq!(htlc_success_txn[2], commitment_txn[0]);
5351         assert_eq!(htlc_success_txn[3], htlc_success_txn[0]);
5352         assert_eq!(htlc_success_txn[4], htlc_success_txn[1]);
5353         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
5354
5355         mine_transaction(&nodes[1], &htlc_timeout_tx);
5356         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5357         expect_pending_htlcs_forwardable!(nodes[1]);
5358         let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5359         assert!(htlc_updates.update_add_htlcs.is_empty());
5360         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5361         let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
5362         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5363         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5364         check_added_monitors!(nodes[1], 1);
5365
5366         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5367         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5368         {
5369                 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5370         }
5371         expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
5372
5373         // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5374         // Note that the fee paid is effectively double as the HTLC value (including the nodes[1] fee
5375         // and nodes[2] fee) is rounded down and then claimed in full.
5376         mine_transaction(&nodes[1], &htlc_success_txn[0]);
5377         expect_payment_forwarded!(nodes[1], nodes[0], Some(196*2), true);
5378         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5379         assert!(updates.update_add_htlcs.is_empty());
5380         assert!(updates.update_fail_htlcs.is_empty());
5381         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5382         assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
5383         assert!(updates.update_fail_malformed_htlcs.is_empty());
5384         check_added_monitors!(nodes[1], 1);
5385
5386         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5387         commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5388
5389         let events = nodes[0].node.get_and_clear_pending_events();
5390         match events[0] {
5391                 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
5392                         assert_eq!(*payment_preimage, our_payment_preimage);
5393                         assert_eq!(*payment_hash, duplicate_payment_hash);
5394                 }
5395                 _ => panic!("Unexpected event"),
5396         }
5397 }
5398
5399 #[test]
5400 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5401         let chanmon_cfgs = create_chanmon_cfgs(2);
5402         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5403         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5404         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5405
5406         // Create some initial channels
5407         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5408
5409         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
5410         let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5411         assert_eq!(local_txn.len(), 1);
5412         assert_eq!(local_txn[0].input.len(), 1);
5413         check_spends!(local_txn[0], chan_1.3);
5414
5415         // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5416         nodes[1].node.claim_funds(payment_preimage);
5417         check_added_monitors!(nodes[1], 1);
5418         mine_transaction(&nodes[1], &local_txn[0]);
5419         check_added_monitors!(nodes[1], 1);
5420         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5421         let events = nodes[1].node.get_and_clear_pending_msg_events();
5422         match events[0] {
5423                 MessageSendEvent::UpdateHTLCs { .. } => {},
5424                 _ => panic!("Unexpected event"),
5425         }
5426         match events[1] {
5427                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5428                 _ => panic!("Unexepected event"),
5429         }
5430         let node_tx = {
5431                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5432                 assert_eq!(node_txn.len(), 3);
5433                 assert_eq!(node_txn[0], node_txn[2]);
5434                 assert_eq!(node_txn[1], local_txn[0]);
5435                 assert_eq!(node_txn[0].input.len(), 1);
5436                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5437                 check_spends!(node_txn[0], local_txn[0]);
5438                 node_txn[0].clone()
5439         };
5440
5441         mine_transaction(&nodes[1], &node_tx);
5442         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
5443
5444         // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5445         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5446         assert_eq!(spend_txn.len(), 1);
5447         assert_eq!(spend_txn[0].input.len(), 1);
5448         check_spends!(spend_txn[0], node_tx);
5449         assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5450 }
5451
5452 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5453         // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5454         // unrevoked commitment transaction.
5455         // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5456         // a remote RAA before they could be failed backwards (and combinations thereof).
5457         // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5458         // use the same payment hashes.
5459         // Thus, we use a six-node network:
5460         //
5461         // A \         / E
5462         //    - C - D -
5463         // B /         \ F
5464         // And test where C fails back to A/B when D announces its latest commitment transaction
5465         let chanmon_cfgs = create_chanmon_cfgs(6);
5466         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5467         // When this test was written, the default base fee floated based on the HTLC count.
5468         // It is now fixed, so we simply set the fee to the expected value here.
5469         let mut config = test_default_channel_config();
5470         config.channel_options.forwarding_fee_base_msat = 196;
5471         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
5472                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5473         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5474
5475         create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5476         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5477         let chan = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5478         create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
5479         create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
5480
5481         // Rebalance and check output sanity...
5482         send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
5483         send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
5484         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 2);
5485
5486         let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
5487         // 0th HTLC:
5488         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
5489         // 1st HTLC:
5490         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
5491         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5492         // 2nd HTLC:
5493         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
5494         // 3rd HTLC:
5495         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
5496         // 4th HTLC:
5497         let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5498         // 5th HTLC:
5499         let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5500         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5501         // 6th HTLC:
5502         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());
5503         // 7th HTLC:
5504         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());
5505
5506         // 8th HTLC:
5507         let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5508         // 9th HTLC:
5509         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5510         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
5511
5512         // 10th HTLC:
5513         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
5514         // 11th HTLC:
5515         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5516         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());
5517
5518         // Double-check that six of the new HTLC were added
5519         // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5520         // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5521         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2).len(), 1);
5522         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 8);
5523
5524         // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5525         // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5526         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_1));
5527         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_3));
5528         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_5));
5529         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_6));
5530         check_added_monitors!(nodes[4], 0);
5531         expect_pending_htlcs_forwardable!(nodes[4]);
5532         check_added_monitors!(nodes[4], 1);
5533
5534         let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5535         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5536         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5537         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5538         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5539         commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5540
5541         // Fail 3rd below-dust and 7th above-dust HTLCs
5542         assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_2));
5543         assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_4));
5544         check_added_monitors!(nodes[5], 0);
5545         expect_pending_htlcs_forwardable!(nodes[5]);
5546         check_added_monitors!(nodes[5], 1);
5547
5548         let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5549         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5550         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5551         commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5552
5553         let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5554
5555         expect_pending_htlcs_forwardable!(nodes[3]);
5556         check_added_monitors!(nodes[3], 1);
5557         let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5558         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5559         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5560         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5561         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5562         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5563         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5564         if deliver_last_raa {
5565                 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5566         } else {
5567                 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5568         }
5569
5570         // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5571         // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5572         // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5573         // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5574         //
5575         // We now broadcast the latest commitment transaction, which *should* result in failures for
5576         // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5577         // the non-broadcast above-dust HTLCs.
5578         //
5579         // Alternatively, we may broadcast the previous commitment transaction, which should only
5580         // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5581         let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5582
5583         if announce_latest {
5584                 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5585         } else {
5586                 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5587         }
5588         let events = nodes[2].node.get_and_clear_pending_events();
5589         let close_event = if deliver_last_raa {
5590                 assert_eq!(events.len(), 2);
5591                 events[1].clone()
5592         } else {
5593                 assert_eq!(events.len(), 1);
5594                 events[0].clone()
5595         };
5596         match close_event {
5597                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5598                 _ => panic!("Unexpected event"),
5599         }
5600
5601         connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5602         check_closed_broadcast!(nodes[2], true);
5603         if deliver_last_raa {
5604                 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5605         } else {
5606                 expect_pending_htlcs_forwardable!(nodes[2]);
5607         }
5608         check_added_monitors!(nodes[2], 3);
5609
5610         let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5611         assert_eq!(cs_msgs.len(), 2);
5612         let mut a_done = false;
5613         for msg in cs_msgs {
5614                 match msg {
5615                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5616                                 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5617                                 // should be failed-backwards here.
5618                                 let target = if *node_id == nodes[0].node.get_our_node_id() {
5619                                         // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5620                                         for htlc in &updates.update_fail_htlcs {
5621                                                 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 });
5622                                         }
5623                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5624                                         assert!(!a_done);
5625                                         a_done = true;
5626                                         &nodes[0]
5627                                 } else {
5628                                         // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5629                                         for htlc in &updates.update_fail_htlcs {
5630                                                 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5631                                         }
5632                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5633                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5634                                         &nodes[1]
5635                                 };
5636                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5637                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5638                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5639                                 if announce_latest {
5640                                         target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5641                                         if *node_id == nodes[0].node.get_our_node_id() {
5642                                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5643                                         }
5644                                 }
5645                                 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5646                         },
5647                         _ => panic!("Unexpected event"),
5648                 }
5649         }
5650
5651         let as_events = nodes[0].node.get_and_clear_pending_events();
5652         assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5653         let mut as_failds = HashSet::new();
5654         let mut as_updates = 0;
5655         for event in as_events.iter() {
5656                 if let &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5657                         assert!(as_failds.insert(*payment_hash));
5658                         if *payment_hash != payment_hash_2 {
5659                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5660                         } else {
5661                                 assert!(!rejected_by_dest);
5662                         }
5663                         if network_update.is_some() {
5664                                 as_updates += 1;
5665                         }
5666                 } else { panic!("Unexpected event"); }
5667         }
5668         assert!(as_failds.contains(&payment_hash_1));
5669         assert!(as_failds.contains(&payment_hash_2));
5670         if announce_latest {
5671                 assert!(as_failds.contains(&payment_hash_3));
5672                 assert!(as_failds.contains(&payment_hash_5));
5673         }
5674         assert!(as_failds.contains(&payment_hash_6));
5675
5676         let bs_events = nodes[1].node.get_and_clear_pending_events();
5677         assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5678         let mut bs_failds = HashSet::new();
5679         let mut bs_updates = 0;
5680         for event in bs_events.iter() {
5681                 if let &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5682                         assert!(bs_failds.insert(*payment_hash));
5683                         if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5684                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5685                         } else {
5686                                 assert!(!rejected_by_dest);
5687                         }
5688                         if network_update.is_some() {
5689                                 bs_updates += 1;
5690                         }
5691                 } else { panic!("Unexpected event"); }
5692         }
5693         assert!(bs_failds.contains(&payment_hash_1));
5694         assert!(bs_failds.contains(&payment_hash_2));
5695         if announce_latest {
5696                 assert!(bs_failds.contains(&payment_hash_4));
5697         }
5698         assert!(bs_failds.contains(&payment_hash_5));
5699
5700         // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5701         // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5702         // unknown-preimage-etc, B should have gotten 2. Thus, in the
5703         // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5704         assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5705         assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5706 }
5707
5708 #[test]
5709 fn test_fail_backwards_latest_remote_announce_a() {
5710         do_test_fail_backwards_unrevoked_remote_announce(false, true);
5711 }
5712
5713 #[test]
5714 fn test_fail_backwards_latest_remote_announce_b() {
5715         do_test_fail_backwards_unrevoked_remote_announce(true, true);
5716 }
5717
5718 #[test]
5719 fn test_fail_backwards_previous_remote_announce() {
5720         do_test_fail_backwards_unrevoked_remote_announce(false, false);
5721         // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5722         // tested for in test_commitment_revoked_fail_backward_exhaustive()
5723 }
5724
5725 #[test]
5726 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5727         let chanmon_cfgs = create_chanmon_cfgs(2);
5728         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5729         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5730         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5731
5732         // Create some initial channels
5733         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5734
5735         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5736         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5737         assert_eq!(local_txn[0].input.len(), 1);
5738         check_spends!(local_txn[0], chan_1.3);
5739
5740         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5741         mine_transaction(&nodes[0], &local_txn[0]);
5742         check_closed_broadcast!(nodes[0], true);
5743         check_added_monitors!(nodes[0], 1);
5744         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5745         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5746
5747         let htlc_timeout = {
5748                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5749                 assert_eq!(node_txn.len(), 2);
5750                 check_spends!(node_txn[0], chan_1.3);
5751                 assert_eq!(node_txn[1].input.len(), 1);
5752                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5753                 check_spends!(node_txn[1], local_txn[0]);
5754                 node_txn[1].clone()
5755         };
5756
5757         mine_transaction(&nodes[0], &htlc_timeout);
5758         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5759         expect_payment_failed!(nodes[0], our_payment_hash, true);
5760
5761         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5762         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5763         assert_eq!(spend_txn.len(), 3);
5764         check_spends!(spend_txn[0], local_txn[0]);
5765         assert_eq!(spend_txn[1].input.len(), 1);
5766         check_spends!(spend_txn[1], htlc_timeout);
5767         assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5768         assert_eq!(spend_txn[2].input.len(), 2);
5769         check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5770         assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5771                 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5772 }
5773
5774 #[test]
5775 fn test_key_derivation_params() {
5776         // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5777         // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5778         // let us re-derive the channel key set to then derive a delayed_payment_key.
5779
5780         let chanmon_cfgs = create_chanmon_cfgs(3);
5781
5782         // We manually create the node configuration to backup the seed.
5783         let seed = [42; 32];
5784         let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5785         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);
5786         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: &chanmon_cfgs[0].network_graph, node_seed: seed, features: InitFeatures::known() };
5787         let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5788         node_cfgs.remove(0);
5789         node_cfgs.insert(0, node);
5790
5791         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5792         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5793
5794         // Create some initial channels
5795         // Create a dummy channel to advance index by one and thus test re-derivation correctness
5796         // for node 0
5797         let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5798         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5799         assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5800
5801         // Ensure all nodes are at the same height
5802         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5803         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5804         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5805         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5806
5807         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5808         let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5809         let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5810         assert_eq!(local_txn_1[0].input.len(), 1);
5811         check_spends!(local_txn_1[0], chan_1.3);
5812
5813         // We check funding pubkey are unique
5814         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]));
5815         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]));
5816         if from_0_funding_key_0 == from_1_funding_key_0
5817             || from_0_funding_key_0 == from_1_funding_key_1
5818             || from_0_funding_key_1 == from_1_funding_key_0
5819             || from_0_funding_key_1 == from_1_funding_key_1 {
5820                 panic!("Funding pubkeys aren't unique");
5821         }
5822
5823         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5824         mine_transaction(&nodes[0], &local_txn_1[0]);
5825         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5826         check_closed_broadcast!(nodes[0], true);
5827         check_added_monitors!(nodes[0], 1);
5828         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5829
5830         let htlc_timeout = {
5831                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5832                 assert_eq!(node_txn[1].input.len(), 1);
5833                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5834                 check_spends!(node_txn[1], local_txn_1[0]);
5835                 node_txn[1].clone()
5836         };
5837
5838         mine_transaction(&nodes[0], &htlc_timeout);
5839         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5840         expect_payment_failed!(nodes[0], our_payment_hash, true);
5841
5842         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5843         let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5844         let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5845         assert_eq!(spend_txn.len(), 3);
5846         check_spends!(spend_txn[0], local_txn_1[0]);
5847         assert_eq!(spend_txn[1].input.len(), 1);
5848         check_spends!(spend_txn[1], htlc_timeout);
5849         assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5850         assert_eq!(spend_txn[2].input.len(), 2);
5851         check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5852         assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5853                 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5854 }
5855
5856 #[test]
5857 fn test_static_output_closing_tx() {
5858         let chanmon_cfgs = create_chanmon_cfgs(2);
5859         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5860         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5861         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5862
5863         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5864
5865         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5866         let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5867
5868         mine_transaction(&nodes[0], &closing_tx);
5869         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5870         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5871
5872         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5873         assert_eq!(spend_txn.len(), 1);
5874         check_spends!(spend_txn[0], closing_tx);
5875
5876         mine_transaction(&nodes[1], &closing_tx);
5877         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5878         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5879
5880         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5881         assert_eq!(spend_txn.len(), 1);
5882         check_spends!(spend_txn[0], closing_tx);
5883 }
5884
5885 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5886         let chanmon_cfgs = create_chanmon_cfgs(2);
5887         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5888         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5889         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5890         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5891
5892         let (payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3000000 });
5893
5894         // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5895         // present in B's local commitment transaction, but none of A's commitment transactions.
5896         assert!(nodes[1].node.claim_funds(payment_preimage));
5897         check_added_monitors!(nodes[1], 1);
5898
5899         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5900         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5901         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
5902
5903         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5904         check_added_monitors!(nodes[0], 1);
5905         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5906         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5907         check_added_monitors!(nodes[1], 1);
5908
5909         let starting_block = nodes[1].best_block_info();
5910         let mut block = Block {
5911                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5912                 txdata: vec![],
5913         };
5914         for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5915                 connect_block(&nodes[1], &block);
5916                 block.header.prev_blockhash = block.block_hash();
5917         }
5918         test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5919         check_closed_broadcast!(nodes[1], true);
5920         check_added_monitors!(nodes[1], 1);
5921         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5922 }
5923
5924 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5925         let chanmon_cfgs = create_chanmon_cfgs(2);
5926         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5927         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5928         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5929         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5930
5931         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5932         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
5933         check_added_monitors!(nodes[0], 1);
5934
5935         let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5936
5937         // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5938         // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5939         // to "time out" the HTLC.
5940
5941         let starting_block = nodes[1].best_block_info();
5942         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5943
5944         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5945                 connect_block(&nodes[0], &Block { header, txdata: Vec::new()});
5946                 header.prev_blockhash = header.block_hash();
5947         }
5948         test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5949         check_closed_broadcast!(nodes[0], true);
5950         check_added_monitors!(nodes[0], 1);
5951         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5952 }
5953
5954 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5955         let chanmon_cfgs = create_chanmon_cfgs(3);
5956         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5957         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5958         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5959         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5960
5961         // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5962         // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5963         // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5964         // actually revoked.
5965         let htlc_value = if use_dust { 50000 } else { 3000000 };
5966         let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5967         assert!(nodes[1].node.fail_htlc_backwards(&our_payment_hash));
5968         expect_pending_htlcs_forwardable!(nodes[1]);
5969         check_added_monitors!(nodes[1], 1);
5970
5971         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5972         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5973         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5974         check_added_monitors!(nodes[0], 1);
5975         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5976         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5977         check_added_monitors!(nodes[1], 1);
5978         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5979         check_added_monitors!(nodes[1], 1);
5980         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5981
5982         if check_revoke_no_close {
5983                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5984                 check_added_monitors!(nodes[0], 1);
5985         }
5986
5987         let starting_block = nodes[1].best_block_info();
5988         let mut block = Block {
5989                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5990                 txdata: vec![],
5991         };
5992         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5993                 connect_block(&nodes[0], &block);
5994                 block.header.prev_blockhash = block.block_hash();
5995         }
5996         if !check_revoke_no_close {
5997                 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5998                 check_closed_broadcast!(nodes[0], true);
5999                 check_added_monitors!(nodes[0], 1);
6000                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6001         } else {
6002                 let events = nodes[0].node.get_and_clear_pending_events();
6003                 assert_eq!(events.len(), 2);
6004                 if let Event::PaymentPathFailed { ref payment_hash, .. } = events[0] {
6005                         assert_eq!(*payment_hash, our_payment_hash);
6006                 } else { panic!("Unexpected event"); }
6007                 if let Event::PaymentFailed { ref payment_hash, .. } = events[1] {
6008                         assert_eq!(*payment_hash, our_payment_hash);
6009                 } else { panic!("Unexpected event"); }
6010         }
6011 }
6012
6013 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
6014 // There are only a few cases to test here:
6015 //  * its not really normative behavior, but we test that below-dust HTLCs "included" in
6016 //    broadcastable commitment transactions result in channel closure,
6017 //  * its included in an unrevoked-but-previous remote commitment transaction,
6018 //  * its included in the latest remote or local commitment transactions.
6019 // We test each of the three possible commitment transactions individually and use both dust and
6020 // non-dust HTLCs.
6021 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
6022 // assume they are handled the same across all six cases, as both outbound and inbound failures are
6023 // tested for at least one of the cases in other tests.
6024 #[test]
6025 fn htlc_claim_single_commitment_only_a() {
6026         do_htlc_claim_local_commitment_only(true);
6027         do_htlc_claim_local_commitment_only(false);
6028
6029         do_htlc_claim_current_remote_commitment_only(true);
6030         do_htlc_claim_current_remote_commitment_only(false);
6031 }
6032
6033 #[test]
6034 fn htlc_claim_single_commitment_only_b() {
6035         do_htlc_claim_previous_remote_commitment_only(true, false);
6036         do_htlc_claim_previous_remote_commitment_only(false, false);
6037         do_htlc_claim_previous_remote_commitment_only(true, true);
6038         do_htlc_claim_previous_remote_commitment_only(false, true);
6039 }
6040
6041 #[test]
6042 #[should_panic]
6043 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
6044         let chanmon_cfgs = create_chanmon_cfgs(2);
6045         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6046         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6047         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6048         // Force duplicate randomness for every get-random call
6049         for node in nodes.iter() {
6050                 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
6051         }
6052
6053         // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
6054         let channel_value_satoshis=10000;
6055         let push_msat=10001;
6056         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
6057         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6058         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
6059         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
6060
6061         // Create a second channel with the same random values. This used to panic due to a colliding
6062         // channel_id, but now panics due to a colliding outbound SCID alias.
6063         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6064 }
6065
6066 #[test]
6067 fn bolt2_open_channel_sending_node_checks_part2() {
6068         let chanmon_cfgs = create_chanmon_cfgs(2);
6069         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6070         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6071         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6072
6073         // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
6074         let channel_value_satoshis=2^24;
6075         let push_msat=10001;
6076         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6077
6078         // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
6079         let channel_value_satoshis=10000;
6080         // Test when push_msat is equal to 1000 * funding_satoshis.
6081         let push_msat=1000*channel_value_satoshis+1;
6082         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6083
6084         // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
6085         let channel_value_satoshis=10000;
6086         let push_msat=10001;
6087         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
6088         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6089         assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
6090
6091         // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
6092         // 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
6093         assert!(node0_to_1_send_open_channel.channel_flags<=1);
6094
6095         // 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.
6096         assert!(BREAKDOWN_TIMEOUT>0);
6097         assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
6098
6099         // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
6100         let chain_hash=genesis_block(Network::Testnet).header.block_hash();
6101         assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
6102
6103         // 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.
6104         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
6105         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
6106         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
6107         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
6108         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
6109 }
6110
6111 #[test]
6112 fn bolt2_open_channel_sane_dust_limit() {
6113         let chanmon_cfgs = create_chanmon_cfgs(2);
6114         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6115         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6116         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6117
6118         let channel_value_satoshis=1000000;
6119         let push_msat=10001;
6120         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
6121         let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6122         node0_to_1_send_open_channel.dust_limit_satoshis = 547;
6123         node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
6124
6125         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
6126         let events = nodes[1].node.get_and_clear_pending_msg_events();
6127         let err_msg = match events[0] {
6128                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
6129                         msg.clone()
6130                 },
6131                 _ => panic!("Unexpected event"),
6132         };
6133         assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
6134 }
6135
6136 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
6137 // originated from our node, its failure is surfaced to the user. We trigger this failure to
6138 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
6139 // is no longer affordable once it's freed.
6140 #[test]
6141 fn test_fail_holding_cell_htlc_upon_free() {
6142         let chanmon_cfgs = create_chanmon_cfgs(2);
6143         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6144         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6145         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6146         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6147
6148         // First nodes[0] generates an update_fee, setting the channel's
6149         // pending_update_fee.
6150         {
6151                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6152                 *feerate_lock += 20;
6153         }
6154         nodes[0].node.timer_tick_occurred();
6155         check_added_monitors!(nodes[0], 1);
6156
6157         let events = nodes[0].node.get_and_clear_pending_msg_events();
6158         assert_eq!(events.len(), 1);
6159         let (update_msg, commitment_signed) = match events[0] {
6160                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6161                         (update_fee.as_ref(), commitment_signed)
6162                 },
6163                 _ => panic!("Unexpected event"),
6164         };
6165
6166         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6167
6168         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6169         let channel_reserve = chan_stat.channel_reserve_msat;
6170         let feerate = get_feerate!(nodes[0], chan.2);
6171         let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6172
6173         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6174         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6175         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6176
6177         // Send a payment which passes reserve checks but gets stuck in the holding cell.
6178         let our_payment_id = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6179         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6180         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6181
6182         // Flush the pending fee update.
6183         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6184         let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6185         check_added_monitors!(nodes[1], 1);
6186         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
6187         check_added_monitors!(nodes[0], 1);
6188
6189         // Upon receipt of the RAA, there will be an attempt to resend the holding cell
6190         // HTLC, but now that the fee has been raised the payment will now fail, causing
6191         // us to surface its failure to the user.
6192         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6193         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6194         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);
6195         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 {}",
6196                 hex::encode(our_payment_hash.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6197         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6198
6199         // Check that the payment failed to be sent out.
6200         let events = nodes[0].node.get_and_clear_pending_events();
6201         assert_eq!(events.len(), 1);
6202         match &events[0] {
6203                 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref rejected_by_dest, ref network_update, ref all_paths_failed, ref short_channel_id, ref error_code, ref error_data, .. } => {
6204                         assert_eq!(our_payment_id, *payment_id.as_ref().unwrap());
6205                         assert_eq!(our_payment_hash.clone(), *payment_hash);
6206                         assert_eq!(*rejected_by_dest, false);
6207                         assert_eq!(*all_paths_failed, true);
6208                         assert_eq!(*network_update, None);
6209                         assert_eq!(*short_channel_id, None);
6210                         assert_eq!(*error_code, None);
6211                         assert_eq!(*error_data, None);
6212                 },
6213                 _ => panic!("Unexpected event"),
6214         }
6215 }
6216
6217 // Test that if multiple HTLCs are released from the holding cell and one is
6218 // valid but the other is no longer valid upon release, the valid HTLC can be
6219 // successfully completed while the other one fails as expected.
6220 #[test]
6221 fn test_free_and_fail_holding_cell_htlcs() {
6222         let chanmon_cfgs = create_chanmon_cfgs(2);
6223         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6224         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6225         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6226         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6227
6228         // First nodes[0] generates an update_fee, setting the channel's
6229         // pending_update_fee.
6230         {
6231                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6232                 *feerate_lock += 200;
6233         }
6234         nodes[0].node.timer_tick_occurred();
6235         check_added_monitors!(nodes[0], 1);
6236
6237         let events = nodes[0].node.get_and_clear_pending_msg_events();
6238         assert_eq!(events.len(), 1);
6239         let (update_msg, commitment_signed) = match events[0] {
6240                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6241                         (update_fee.as_ref(), commitment_signed)
6242                 },
6243                 _ => panic!("Unexpected event"),
6244         };
6245
6246         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6247
6248         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6249         let channel_reserve = chan_stat.channel_reserve_msat;
6250         let feerate = get_feerate!(nodes[0], chan.2);
6251         let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6252
6253         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6254         let amt_1 = 20000;
6255         let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors) - amt_1;
6256         let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
6257         let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
6258
6259         // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6260         nodes[0].node.send_payment(&route_1, payment_hash_1, &Some(payment_secret_1)).unwrap();
6261         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6262         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6263         let payment_id_2 = nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
6264         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6265         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6266
6267         // Flush the pending fee update.
6268         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6269         let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6270         check_added_monitors!(nodes[1], 1);
6271         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6272         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6273         check_added_monitors!(nodes[0], 2);
6274
6275         // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6276         // but now that the fee has been raised the second payment will now fail, causing us
6277         // to surface its failure to the user. The first payment should succeed.
6278         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6279         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6280         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);
6281         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 {}",
6282                 hex::encode(payment_hash_2.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6283         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6284
6285         // Check that the second payment failed to be sent out.
6286         let events = nodes[0].node.get_and_clear_pending_events();
6287         assert_eq!(events.len(), 1);
6288         match &events[0] {
6289                 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref rejected_by_dest, ref network_update, ref all_paths_failed, ref short_channel_id, ref error_code, ref error_data, .. } => {
6290                         assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
6291                         assert_eq!(payment_hash_2.clone(), *payment_hash);
6292                         assert_eq!(*rejected_by_dest, false);
6293                         assert_eq!(*all_paths_failed, true);
6294                         assert_eq!(*network_update, None);
6295                         assert_eq!(*short_channel_id, None);
6296                         assert_eq!(*error_code, None);
6297                         assert_eq!(*error_data, None);
6298                 },
6299                 _ => panic!("Unexpected event"),
6300         }
6301
6302         // Complete the first payment and the RAA from the fee update.
6303         let (payment_event, send_raa_event) = {
6304                 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6305                 assert_eq!(msgs.len(), 2);
6306                 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6307         };
6308         let raa = match send_raa_event {
6309                 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6310                 _ => panic!("Unexpected event"),
6311         };
6312         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6313         check_added_monitors!(nodes[1], 1);
6314         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6315         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6316         let events = nodes[1].node.get_and_clear_pending_events();
6317         assert_eq!(events.len(), 1);
6318         match events[0] {
6319                 Event::PendingHTLCsForwardable { .. } => {},
6320                 _ => panic!("Unexpected event"),
6321         }
6322         nodes[1].node.process_pending_htlc_forwards();
6323         let events = nodes[1].node.get_and_clear_pending_events();
6324         assert_eq!(events.len(), 1);
6325         match events[0] {
6326                 Event::PaymentReceived { .. } => {},
6327                 _ => panic!("Unexpected event"),
6328         }
6329         nodes[1].node.claim_funds(payment_preimage_1);
6330         check_added_monitors!(nodes[1], 1);
6331         let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6332         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6333         commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6334         expect_payment_sent!(nodes[0], payment_preimage_1);
6335 }
6336
6337 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6338 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6339 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6340 // once it's freed.
6341 #[test]
6342 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6343         let chanmon_cfgs = create_chanmon_cfgs(3);
6344         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6345         // When this test was written, the default base fee floated based on the HTLC count.
6346         // It is now fixed, so we simply set the fee to the expected value here.
6347         let mut config = test_default_channel_config();
6348         config.channel_options.forwarding_fee_base_msat = 196;
6349         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
6350         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6351         let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6352         let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6353
6354         // First nodes[1] generates an update_fee, setting the channel's
6355         // pending_update_fee.
6356         {
6357                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
6358                 *feerate_lock += 20;
6359         }
6360         nodes[1].node.timer_tick_occurred();
6361         check_added_monitors!(nodes[1], 1);
6362
6363         let events = nodes[1].node.get_and_clear_pending_msg_events();
6364         assert_eq!(events.len(), 1);
6365         let (update_msg, commitment_signed) = match events[0] {
6366                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6367                         (update_fee.as_ref(), commitment_signed)
6368                 },
6369                 _ => panic!("Unexpected event"),
6370         };
6371
6372         nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6373
6374         let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
6375         let channel_reserve = chan_stat.channel_reserve_msat;
6376         let feerate = get_feerate!(nodes[0], chan_0_1.2);
6377         let opt_anchors = get_opt_anchors!(nodes[0], chan_0_1.2);
6378
6379         // Send a payment which passes reserve checks but gets stuck in the holding cell.
6380         let feemsat = 239;
6381         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
6382         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors) - total_routing_fee_msat;
6383         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
6384         let payment_event = {
6385                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6386                 check_added_monitors!(nodes[0], 1);
6387
6388                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6389                 assert_eq!(events.len(), 1);
6390
6391                 SendEvent::from_event(events.remove(0))
6392         };
6393         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6394         check_added_monitors!(nodes[1], 0);
6395         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6396         expect_pending_htlcs_forwardable!(nodes[1]);
6397
6398         chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
6399         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6400
6401         // Flush the pending fee update.
6402         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6403         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6404         check_added_monitors!(nodes[2], 1);
6405         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6406         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6407         check_added_monitors!(nodes[1], 2);
6408
6409         // A final RAA message is generated to finalize the fee update.
6410         let events = nodes[1].node.get_and_clear_pending_msg_events();
6411         assert_eq!(events.len(), 1);
6412
6413         let raa_msg = match &events[0] {
6414                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6415                         msg.clone()
6416                 },
6417                 _ => panic!("Unexpected event"),
6418         };
6419
6420         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6421         check_added_monitors!(nodes[2], 1);
6422         assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6423
6424         // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6425         let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6426         assert_eq!(process_htlc_forwards_event.len(), 1);
6427         match &process_htlc_forwards_event[0] {
6428                 &Event::PendingHTLCsForwardable { .. } => {},
6429                 _ => panic!("Unexpected event"),
6430         }
6431
6432         // In response, we call ChannelManager's process_pending_htlc_forwards
6433         nodes[1].node.process_pending_htlc_forwards();
6434         check_added_monitors!(nodes[1], 1);
6435
6436         // This causes the HTLC to be failed backwards.
6437         let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6438         assert_eq!(fail_event.len(), 1);
6439         let (fail_msg, commitment_signed) = match &fail_event[0] {
6440                 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6441                         assert_eq!(updates.update_add_htlcs.len(), 0);
6442                         assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6443                         assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6444                         assert_eq!(updates.update_fail_htlcs.len(), 1);
6445                         (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6446                 },
6447                 _ => panic!("Unexpected event"),
6448         };
6449
6450         // Pass the failure messages back to nodes[0].
6451         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6452         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6453
6454         // Complete the HTLC failure+removal process.
6455         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6456         check_added_monitors!(nodes[0], 1);
6457         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6458         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6459         check_added_monitors!(nodes[1], 2);
6460         let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6461         assert_eq!(final_raa_event.len(), 1);
6462         let raa = match &final_raa_event[0] {
6463                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6464                 _ => panic!("Unexpected event"),
6465         };
6466         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6467         expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6468         check_added_monitors!(nodes[0], 1);
6469 }
6470
6471 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6472 // 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.
6473 //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.
6474
6475 #[test]
6476 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6477         //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6478         let chanmon_cfgs = create_chanmon_cfgs(2);
6479         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6480         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6481         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6482         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6483
6484         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6485         route.paths[0][0].fee_msat = 100;
6486
6487         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6488                 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6489         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6490         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6491 }
6492
6493 #[test]
6494 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6495         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6496         let chanmon_cfgs = create_chanmon_cfgs(2);
6497         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6498         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6499         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6500         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6501
6502         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6503         route.paths[0][0].fee_msat = 0;
6504         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6505                 assert_eq!(err, "Cannot send 0-msat HTLC"));
6506
6507         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6508         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6509 }
6510
6511 #[test]
6512 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6513         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6514         let chanmon_cfgs = create_chanmon_cfgs(2);
6515         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6516         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6517         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6518         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6519
6520         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6521         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6522         check_added_monitors!(nodes[0], 1);
6523         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6524         updates.update_add_htlcs[0].amount_msat = 0;
6525
6526         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6527         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6528         check_closed_broadcast!(nodes[1], true).unwrap();
6529         check_added_monitors!(nodes[1], 1);
6530         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
6531 }
6532
6533 #[test]
6534 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6535         //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6536         //It is enforced when constructing a route.
6537         let chanmon_cfgs = create_chanmon_cfgs(2);
6538         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6539         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6540         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6541         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6542
6543         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
6544                 .with_features(InvoiceFeatures::known());
6545         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000, 0);
6546         route.paths[0].last_mut().unwrap().cltv_expiry_delta = 500000001;
6547         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::RouteError { ref err },
6548                 assert_eq!(err, &"Channel CLTV overflowed?"));
6549 }
6550
6551 #[test]
6552 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6553         //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.
6554         //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6555         //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6556         let chanmon_cfgs = create_chanmon_cfgs(2);
6557         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6558         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6559         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6560         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6561         let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6562
6563         for i in 0..max_accepted_htlcs {
6564                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6565                 let payment_event = {
6566                         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6567                         check_added_monitors!(nodes[0], 1);
6568
6569                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6570                         assert_eq!(events.len(), 1);
6571                         if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6572                                 assert_eq!(htlcs[0].htlc_id, i);
6573                         } else {
6574                                 assert!(false);
6575                         }
6576                         SendEvent::from_event(events.remove(0))
6577                 };
6578                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6579                 check_added_monitors!(nodes[1], 0);
6580                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6581
6582                 expect_pending_htlcs_forwardable!(nodes[1]);
6583                 expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6584         }
6585         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6586         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6587                 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6588
6589         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6590         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6591 }
6592
6593 #[test]
6594 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6595         //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.
6596         let chanmon_cfgs = create_chanmon_cfgs(2);
6597         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6598         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6599         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6600         let channel_value = 100000;
6601         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::known(), InitFeatures::known());
6602         let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6603
6604         send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6605
6606         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6607         // Manually create a route over our max in flight (which our router normally automatically
6608         // limits us to.
6609         route.paths[0][0].fee_msat =  max_in_flight + 1;
6610         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6611                 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)));
6612
6613         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6614         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);
6615
6616         send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6617 }
6618
6619 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6620 #[test]
6621 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6622         //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6623         let chanmon_cfgs = create_chanmon_cfgs(2);
6624         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6625         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6626         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6627         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6628         let htlc_minimum_msat: u64;
6629         {
6630                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6631                 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6632                 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6633         }
6634
6635         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6636         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6637         check_added_monitors!(nodes[0], 1);
6638         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6639         updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6640         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6641         assert!(nodes[1].node.list_channels().is_empty());
6642         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6643         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()));
6644         check_added_monitors!(nodes[1], 1);
6645         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6646 }
6647
6648 #[test]
6649 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6650         //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
6651         let chanmon_cfgs = create_chanmon_cfgs(2);
6652         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6653         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6654         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6655         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6656
6657         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6658         let channel_reserve = chan_stat.channel_reserve_msat;
6659         let feerate = get_feerate!(nodes[0], chan.2);
6660         let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6661         // The 2* and +1 are for the fee spike reserve.
6662         let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6663
6664         let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6665         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6666         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6667         check_added_monitors!(nodes[0], 1);
6668         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6669
6670         // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6671         // at this time channel-initiatee receivers are not required to enforce that senders
6672         // respect the fee_spike_reserve.
6673         updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6674         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6675
6676         assert!(nodes[1].node.list_channels().is_empty());
6677         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6678         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6679         check_added_monitors!(nodes[1], 1);
6680         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6681 }
6682
6683 #[test]
6684 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6685         //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6686         //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6687         let chanmon_cfgs = create_chanmon_cfgs(2);
6688         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6689         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6690         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6691         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6692
6693         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3999999);
6694         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6695         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6696         let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6697         let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &Some(our_payment_secret), cur_height, &None).unwrap();
6698         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6699
6700         let mut msg = msgs::UpdateAddHTLC {
6701                 channel_id: chan.2,
6702                 htlc_id: 0,
6703                 amount_msat: 1000,
6704                 payment_hash: our_payment_hash,
6705                 cltv_expiry: htlc_cltv,
6706                 onion_routing_packet: onion_packet.clone(),
6707         };
6708
6709         for i in 0..super::channel::OUR_MAX_HTLCS {
6710                 msg.htlc_id = i as u64;
6711                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6712         }
6713         msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6714         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6715
6716         assert!(nodes[1].node.list_channels().is_empty());
6717         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6718         assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6719         check_added_monitors!(nodes[1], 1);
6720         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6721 }
6722
6723 #[test]
6724 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6725         //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6726         let chanmon_cfgs = create_chanmon_cfgs(2);
6727         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6728         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6729         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6730         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6731
6732         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6733         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6734         check_added_monitors!(nodes[0], 1);
6735         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6736         updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6737         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6738
6739         assert!(nodes[1].node.list_channels().is_empty());
6740         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6741         assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6742         check_added_monitors!(nodes[1], 1);
6743         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6744 }
6745
6746 #[test]
6747 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6748         //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6749         let chanmon_cfgs = create_chanmon_cfgs(2);
6750         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6751         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6752         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6753
6754         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6755         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6756         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6757         check_added_monitors!(nodes[0], 1);
6758         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6759         updates.update_add_htlcs[0].cltv_expiry = 500000000;
6760         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6761
6762         assert!(nodes[1].node.list_channels().is_empty());
6763         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6764         assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6765         check_added_monitors!(nodes[1], 1);
6766         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6767 }
6768
6769 #[test]
6770 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6771         //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6772         // We test this by first testing that that repeated HTLCs pass commitment signature checks
6773         // after disconnect and that non-sequential htlc_ids result in a channel failure.
6774         let chanmon_cfgs = create_chanmon_cfgs(2);
6775         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6776         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6777         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6778
6779         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6780         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6781         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6782         check_added_monitors!(nodes[0], 1);
6783         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6784         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6785
6786         //Disconnect and Reconnect
6787         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6788         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6789         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
6790         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6791         assert_eq!(reestablish_1.len(), 1);
6792         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
6793         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6794         assert_eq!(reestablish_2.len(), 1);
6795         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6796         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6797         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6798         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6799
6800         //Resend HTLC
6801         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6802         assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6803         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6804         check_added_monitors!(nodes[1], 1);
6805         let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6806
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!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
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_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6818         //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.
6819
6820         let chanmon_cfgs = create_chanmon_cfgs(2);
6821         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6822         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6823         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6824         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6825         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6826         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6827
6828         check_added_monitors!(nodes[0], 1);
6829         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6830         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6831
6832         let update_msg = msgs::UpdateFulfillHTLC{
6833                 channel_id: chan.2,
6834                 htlc_id: 0,
6835                 payment_preimage: our_payment_preimage,
6836         };
6837
6838         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6839
6840         assert!(nodes[0].node.list_channels().is_empty());
6841         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6842         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()));
6843         check_added_monitors!(nodes[0], 1);
6844         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6845 }
6846
6847 #[test]
6848 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6849         //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.
6850
6851         let chanmon_cfgs = create_chanmon_cfgs(2);
6852         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6853         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6854         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6855         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6856
6857         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6858         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6859         check_added_monitors!(nodes[0], 1);
6860         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6861         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6862
6863         let update_msg = msgs::UpdateFailHTLC{
6864                 channel_id: chan.2,
6865                 htlc_id: 0,
6866                 reason: msgs::OnionErrorPacket { data: Vec::new()},
6867         };
6868
6869         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6870
6871         assert!(nodes[0].node.list_channels().is_empty());
6872         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6873         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()));
6874         check_added_monitors!(nodes[0], 1);
6875         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6876 }
6877
6878 #[test]
6879 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6880         //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.
6881
6882         let chanmon_cfgs = create_chanmon_cfgs(2);
6883         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6884         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6885         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6886         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6887
6888         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6889         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6890         check_added_monitors!(nodes[0], 1);
6891         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6892         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6893         let update_msg = msgs::UpdateFailMalformedHTLC{
6894                 channel_id: chan.2,
6895                 htlc_id: 0,
6896                 sha256_of_onion: [1; 32],
6897                 failure_code: 0x8000,
6898         };
6899
6900         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6901
6902         assert!(nodes[0].node.list_channels().is_empty());
6903         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6904         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()));
6905         check_added_monitors!(nodes[0], 1);
6906         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6907 }
6908
6909 #[test]
6910 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6911         //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6912
6913         let chanmon_cfgs = create_chanmon_cfgs(2);
6914         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6915         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6916         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6917         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6918
6919         let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6920
6921         nodes[1].node.claim_funds(our_payment_preimage);
6922         check_added_monitors!(nodes[1], 1);
6923
6924         let events = nodes[1].node.get_and_clear_pending_msg_events();
6925         assert_eq!(events.len(), 1);
6926         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6927                 match events[0] {
6928                         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, .. } } => {
6929                                 assert!(update_add_htlcs.is_empty());
6930                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6931                                 assert!(update_fail_htlcs.is_empty());
6932                                 assert!(update_fail_malformed_htlcs.is_empty());
6933                                 assert!(update_fee.is_none());
6934                                 update_fulfill_htlcs[0].clone()
6935                         },
6936                         _ => panic!("Unexpected event"),
6937                 }
6938         };
6939
6940         update_fulfill_msg.htlc_id = 1;
6941
6942         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6943
6944         assert!(nodes[0].node.list_channels().is_empty());
6945         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6946         assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6947         check_added_monitors!(nodes[0], 1);
6948         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6949 }
6950
6951 #[test]
6952 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6953         //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.
6954
6955         let chanmon_cfgs = create_chanmon_cfgs(2);
6956         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6957         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6958         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6959         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6960
6961         let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6962
6963         nodes[1].node.claim_funds(our_payment_preimage);
6964         check_added_monitors!(nodes[1], 1);
6965
6966         let events = nodes[1].node.get_and_clear_pending_msg_events();
6967         assert_eq!(events.len(), 1);
6968         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6969                 match events[0] {
6970                         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, .. } } => {
6971                                 assert!(update_add_htlcs.is_empty());
6972                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6973                                 assert!(update_fail_htlcs.is_empty());
6974                                 assert!(update_fail_malformed_htlcs.is_empty());
6975                                 assert!(update_fee.is_none());
6976                                 update_fulfill_htlcs[0].clone()
6977                         },
6978                         _ => panic!("Unexpected event"),
6979                 }
6980         };
6981
6982         update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6983
6984         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6985
6986         assert!(nodes[0].node.list_channels().is_empty());
6987         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6988         assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6989         check_added_monitors!(nodes[0], 1);
6990         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6991 }
6992
6993 #[test]
6994 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6995         //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.
6996
6997         let chanmon_cfgs = create_chanmon_cfgs(2);
6998         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6999         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7000         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7001         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7002
7003         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
7004         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7005         check_added_monitors!(nodes[0], 1);
7006
7007         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7008         updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
7009
7010         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
7011         check_added_monitors!(nodes[1], 0);
7012         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
7013
7014         let events = nodes[1].node.get_and_clear_pending_msg_events();
7015
7016         let mut update_msg: msgs::UpdateFailMalformedHTLC = {
7017                 match events[0] {
7018                         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, .. } } => {
7019                                 assert!(update_add_htlcs.is_empty());
7020                                 assert!(update_fulfill_htlcs.is_empty());
7021                                 assert!(update_fail_htlcs.is_empty());
7022                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
7023                                 assert!(update_fee.is_none());
7024                                 update_fail_malformed_htlcs[0].clone()
7025                         },
7026                         _ => panic!("Unexpected event"),
7027                 }
7028         };
7029         update_msg.failure_code &= !0x8000;
7030         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
7031
7032         assert!(nodes[0].node.list_channels().is_empty());
7033         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
7034         assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
7035         check_added_monitors!(nodes[0], 1);
7036         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
7037 }
7038
7039 #[test]
7040 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
7041         //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
7042         //    * 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.
7043
7044         let chanmon_cfgs = create_chanmon_cfgs(3);
7045         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7046         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7047         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7048         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7049         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7050
7051         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
7052
7053         //First hop
7054         let mut payment_event = {
7055                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7056                 check_added_monitors!(nodes[0], 1);
7057                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7058                 assert_eq!(events.len(), 1);
7059                 SendEvent::from_event(events.remove(0))
7060         };
7061         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7062         check_added_monitors!(nodes[1], 0);
7063         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7064         expect_pending_htlcs_forwardable!(nodes[1]);
7065         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7066         assert_eq!(events_2.len(), 1);
7067         check_added_monitors!(nodes[1], 1);
7068         payment_event = SendEvent::from_event(events_2.remove(0));
7069         assert_eq!(payment_event.msgs.len(), 1);
7070
7071         //Second Hop
7072         payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
7073         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
7074         check_added_monitors!(nodes[2], 0);
7075         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
7076
7077         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
7078         assert_eq!(events_3.len(), 1);
7079         let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
7080                 match events_3[0] {
7081                         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 } } => {
7082                                 assert!(update_add_htlcs.is_empty());
7083                                 assert!(update_fulfill_htlcs.is_empty());
7084                                 assert!(update_fail_htlcs.is_empty());
7085                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
7086                                 assert!(update_fee.is_none());
7087                                 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
7088                         },
7089                         _ => panic!("Unexpected event"),
7090                 }
7091         };
7092
7093         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
7094
7095         check_added_monitors!(nodes[1], 0);
7096         commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
7097         expect_pending_htlcs_forwardable!(nodes[1]);
7098         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
7099         assert_eq!(events_4.len(), 1);
7100
7101         //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
7102         match events_4[0] {
7103                 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, .. } } => {
7104                         assert!(update_add_htlcs.is_empty());
7105                         assert!(update_fulfill_htlcs.is_empty());
7106                         assert_eq!(update_fail_htlcs.len(), 1);
7107                         assert!(update_fail_malformed_htlcs.is_empty());
7108                         assert!(update_fee.is_none());
7109                 },
7110                 _ => panic!("Unexpected event"),
7111         };
7112
7113         check_added_monitors!(nodes[1], 1);
7114 }
7115
7116 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
7117         // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
7118         // 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
7119         // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
7120
7121         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7122         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7123         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7124         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7125         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7126         let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7127
7128         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7129
7130         // We route 2 dust-HTLCs between A and B
7131         let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7132         let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7133         route_payment(&nodes[0], &[&nodes[1]], 1000000);
7134
7135         // Cache one local commitment tx as previous
7136         let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7137
7138         // Fail one HTLC to prune it in the will-be-latest-local commitment tx
7139         assert!(nodes[1].node.fail_htlc_backwards(&payment_hash_2));
7140         check_added_monitors!(nodes[1], 0);
7141         expect_pending_htlcs_forwardable!(nodes[1]);
7142         check_added_monitors!(nodes[1], 1);
7143
7144         let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7145         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
7146         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
7147         check_added_monitors!(nodes[0], 1);
7148
7149         // Cache one local commitment tx as lastest
7150         let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7151
7152         let events = nodes[0].node.get_and_clear_pending_msg_events();
7153         match events[0] {
7154                 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
7155                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7156                 },
7157                 _ => panic!("Unexpected event"),
7158         }
7159         match events[1] {
7160                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
7161                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7162                 },
7163                 _ => panic!("Unexpected event"),
7164         }
7165
7166         assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
7167         // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7168         if announce_latest {
7169                 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
7170         } else {
7171                 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
7172         }
7173
7174         check_closed_broadcast!(nodes[0], true);
7175         check_added_monitors!(nodes[0], 1);
7176         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7177
7178         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7179         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7180         let events = nodes[0].node.get_and_clear_pending_events();
7181         // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
7182         assert_eq!(events.len(), 2);
7183         let mut first_failed = false;
7184         for event in events {
7185                 match event {
7186                         Event::PaymentPathFailed { payment_hash, .. } => {
7187                                 if payment_hash == payment_hash_1 {
7188                                         assert!(!first_failed);
7189                                         first_failed = true;
7190                                 } else {
7191                                         assert_eq!(payment_hash, payment_hash_2);
7192                                 }
7193                         }
7194                         _ => panic!("Unexpected event"),
7195                 }
7196         }
7197 }
7198
7199 #[test]
7200 fn test_failure_delay_dust_htlc_local_commitment() {
7201         do_test_failure_delay_dust_htlc_local_commitment(true);
7202         do_test_failure_delay_dust_htlc_local_commitment(false);
7203 }
7204
7205 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7206         // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7207         // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7208         // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7209         // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7210         // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7211         // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7212
7213         let chanmon_cfgs = create_chanmon_cfgs(3);
7214         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7215         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7216         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7217         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7218
7219         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7220
7221         let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7222         let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7223
7224         let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7225         let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7226
7227         // We revoked bs_commitment_tx
7228         if revoked {
7229                 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7230                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
7231         }
7232
7233         let mut timeout_tx = Vec::new();
7234         if local {
7235                 // We fail dust-HTLC 1 by broadcast of local commitment tx
7236                 mine_transaction(&nodes[0], &as_commitment_tx[0]);
7237                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7238                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7239                 expect_payment_failed!(nodes[0], dust_hash, true);
7240
7241                 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
7242                 check_closed_broadcast!(nodes[0], true);
7243                 check_added_monitors!(nodes[0], 1);
7244                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7245                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
7246                 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7247                 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7248                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7249                 mine_transaction(&nodes[0], &timeout_tx[0]);
7250                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7251                 expect_payment_failed!(nodes[0], non_dust_hash, true);
7252         } else {
7253                 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7254                 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
7255                 check_closed_broadcast!(nodes[0], true);
7256                 check_added_monitors!(nodes[0], 1);
7257                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7258                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7259                 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7260                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
7261                 if !revoked {
7262                         expect_payment_failed!(nodes[0], dust_hash, true);
7263                         assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7264                         // We fail non-dust-HTLC 2 by broadcast of local timeout tx on remote commitment tx
7265                         mine_transaction(&nodes[0], &timeout_tx[0]);
7266                         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7267                         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7268                         expect_payment_failed!(nodes[0], non_dust_hash, true);
7269                 } else {
7270                         // If revoked, both dust & non-dust HTLCs should have been failed after ANTI_REORG_DELAY confs of revoked
7271                         // commitment tx
7272                         let events = nodes[0].node.get_and_clear_pending_events();
7273                         assert_eq!(events.len(), 2);
7274                         let first;
7275                         match events[0] {
7276                                 Event::PaymentPathFailed { payment_hash, .. } => {
7277                                         if payment_hash == dust_hash { first = true; }
7278                                         else { first = false; }
7279                                 },
7280                                 _ => panic!("Unexpected event"),
7281                         }
7282                         match events[1] {
7283                                 Event::PaymentPathFailed { payment_hash, .. } => {
7284                                         if first { assert_eq!(payment_hash, non_dust_hash); }
7285                                         else { assert_eq!(payment_hash, dust_hash); }
7286                                 },
7287                                 _ => panic!("Unexpected event"),
7288                         }
7289                 }
7290         }
7291 }
7292
7293 #[test]
7294 fn test_sweep_outbound_htlc_failure_update() {
7295         do_test_sweep_outbound_htlc_failure_update(false, true);
7296         do_test_sweep_outbound_htlc_failure_update(false, false);
7297         do_test_sweep_outbound_htlc_failure_update(true, false);
7298 }
7299
7300 #[test]
7301 fn test_user_configurable_csv_delay() {
7302         // We test our channel constructors yield errors when we pass them absurd csv delay
7303
7304         let mut low_our_to_self_config = UserConfig::default();
7305         low_our_to_self_config.own_channel_config.our_to_self_delay = 6;
7306         let mut high_their_to_self_config = UserConfig::default();
7307         high_their_to_self_config.peer_channel_config_limits.their_to_self_delay = 100;
7308         let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7309         let chanmon_cfgs = create_chanmon_cfgs(2);
7310         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7311         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7312         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7313
7314         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7315         if let Err(error) = Channel::new_outbound(&&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) },
7316                 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), 1000000, 1000000, 0,
7317                 &low_our_to_self_config, 0, 42)
7318         {
7319                 match error {
7320                         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())); },
7321                         _ => panic!("Unexpected event"),
7322                 }
7323         } else { assert!(false) }
7324
7325         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7326         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7327         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7328         open_channel.to_self_delay = 200;
7329         if let Err(error) = Channel::new_from_req(&&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) },
7330                 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), &open_channel, 0,
7331                 &low_our_to_self_config, 0, &nodes[0].logger, 42)
7332         {
7333                 match error {
7334                         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()));  },
7335                         _ => panic!("Unexpected event"),
7336                 }
7337         } else { assert!(false); }
7338
7339         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7340         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7341         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id()));
7342         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7343         accept_channel.to_self_delay = 200;
7344         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7345         let reason_msg;
7346         if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7347                 match action {
7348                         &ErrorAction::SendErrorMessage { ref msg } => {
7349                                 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()));
7350                                 reason_msg = msg.data.clone();
7351                         },
7352                         _ => { panic!(); }
7353                 }
7354         } else { panic!(); }
7355         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg });
7356
7357         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7358         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7359         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7360         open_channel.to_self_delay = 200;
7361         if let Err(error) = Channel::new_from_req(&&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) },
7362                 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), &open_channel, 0,
7363                 &high_their_to_self_config, 0, &nodes[0].logger, 42)
7364         {
7365                 match error {
7366                         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())); },
7367                         _ => panic!("Unexpected event"),
7368                 }
7369         } else { assert!(false); }
7370 }
7371
7372 #[test]
7373 fn test_data_loss_protect() {
7374         // We want to be sure that :
7375         // * we don't broadcast our Local Commitment Tx in case of fallen behind
7376         //   (but this is not quite true - we broadcast during Drop because chanmon is out of sync with chanmgr)
7377         // * we close channel in case of detecting other being fallen behind
7378         // * we are able to claim our own outputs thanks to to_remote being static
7379         // TODO: this test is incomplete and the data_loss_protect implementation is incomplete - see issue #775
7380         let persister;
7381         let logger;
7382         let fee_estimator;
7383         let tx_broadcaster;
7384         let chain_source;
7385         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7386         // We broadcast during Drop because chanmon is out of sync with chanmgr, which would cause a panic
7387         // during signing due to revoked tx
7388         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7389         let keys_manager = &chanmon_cfgs[0].keys_manager;
7390         let monitor;
7391         let node_state_0;
7392         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7393         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7394         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7395
7396         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7397
7398         // Cache node A state before any channel update
7399         let previous_node_state = nodes[0].node.encode();
7400         let mut previous_chain_monitor_state = test_utils::TestVecWriter(Vec::new());
7401         get_monitor!(nodes[0], chan.2).write(&mut previous_chain_monitor_state).unwrap();
7402
7403         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7404         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7405
7406         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7407         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7408
7409         // Restore node A from previous state
7410         logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7411         let mut chain_monitor = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut io::Cursor::new(previous_chain_monitor_state.0), keys_manager).unwrap().1;
7412         chain_source = test_utils::TestChainSource::new(Network::Testnet);
7413         tx_broadcaster = test_utils::TestBroadcaster { txn_broadcasted: Mutex::new(Vec::new()), blocks: Arc::new(Mutex::new(Vec::new())) };
7414         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
7415         persister = test_utils::TestPersister::new();
7416         monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &tx_broadcaster, &logger, &fee_estimator, &persister, keys_manager);
7417         node_state_0 = {
7418                 let mut channel_monitors = HashMap::new();
7419                 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chain_monitor);
7420                 <(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 {
7421                         keys_manager: keys_manager,
7422                         fee_estimator: &fee_estimator,
7423                         chain_monitor: &monitor,
7424                         logger: &logger,
7425                         tx_broadcaster: &tx_broadcaster,
7426                         default_config: UserConfig::default(),
7427                         channel_monitors,
7428                 }).unwrap().1
7429         };
7430         nodes[0].node = &node_state_0;
7431         assert!(monitor.watch_channel(OutPoint { txid: chan.3.txid(), index: 0 }, chain_monitor).is_ok());
7432         nodes[0].chain_monitor = &monitor;
7433         nodes[0].chain_source = &chain_source;
7434
7435         check_added_monitors!(nodes[0], 1);
7436
7437         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7438         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7439
7440         let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7441
7442         // Check we don't broadcast any transactions following learning of per_commitment_point from B
7443         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7444         check_added_monitors!(nodes[0], 1);
7445
7446         {
7447                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7448                 assert_eq!(node_txn.len(), 0);
7449         }
7450
7451         let mut reestablish_1 = Vec::with_capacity(1);
7452         for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7453                 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
7454                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7455                         reestablish_1.push(msg.clone());
7456                 } else if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7457                 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7458                         match action {
7459                                 &ErrorAction::SendErrorMessage { ref msg } => {
7460                                         assert_eq!(msg.data, "We have fallen behind - we have received proof that if we broadcast remote is going to claim our funds - we can't do any automated broadcasting");
7461                                 },
7462                                 _ => panic!("Unexpected event!"),
7463                         }
7464                 } else {
7465                         panic!("Unexpected event")
7466                 }
7467         }
7468
7469         // Check we close channel detecting A is fallen-behind
7470         // Check that we sent the warning message when we detected that A has fallen behind,
7471         // and give the possibility for A to recover from the warning.
7472         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7473         let warn_msg = "Peer attempted to reestablish channel with a very old local commitment transaction".to_owned();
7474         assert!(check_warn_msg!(nodes[1], nodes[0].node.get_our_node_id(), chan.2).contains(&warn_msg));
7475
7476         // Check A is able to claim to_remote output
7477         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7478         // The node B should not broadcast the transaction to force close the channel!
7479         assert!(node_txn.is_empty());
7480         // B should now detect that there is something wrong and should force close the channel.
7481         let exp_err = "We have fallen behind - we have received proof that if we broadcast remote is going to claim our funds - we can\'t do any automated broadcasting";
7482         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: exp_err.to_string() });
7483
7484         // after the warning message sent by B, we should not able to
7485         // use the channel, or reconnect with success to the channel.
7486         assert!(nodes[0].node.list_usable_channels().is_empty());
7487         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7488         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7489         let retry_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7490
7491         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &retry_reestablish[0]);
7492         let mut err_msgs_0 = Vec::with_capacity(1);
7493         for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7494                 if let MessageSendEvent::HandleError { ref action, .. } = msg {
7495                         match action {
7496                                 &ErrorAction::SendErrorMessage { ref msg } => {
7497                                         assert_eq!(msg.data, "Failed to find corresponding channel");
7498                                         err_msgs_0.push(msg.clone());
7499                                 },
7500                                 _ => panic!("Unexpected event!"),
7501                         }
7502                 } else {
7503                         panic!("Unexpected event!");
7504                 }
7505         }
7506         assert_eq!(err_msgs_0.len(), 1);
7507         nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), &err_msgs_0[0]);
7508         assert!(nodes[1].node.list_usable_channels().is_empty());
7509         check_added_monitors!(nodes[1], 1);
7510         check_closed_event!(nodes[1], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "Failed to find corresponding channel".to_owned() });
7511         check_closed_broadcast!(nodes[1], false);
7512 }
7513
7514 #[test]
7515 fn test_check_htlc_underpaying() {
7516         // Send payment through A -> B but A is maliciously
7517         // sending a probe payment (i.e less than expected value0
7518         // to B, B should refuse payment.
7519
7520         let chanmon_cfgs = create_chanmon_cfgs(2);
7521         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7522         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7523         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7524
7525         // Create some initial channels
7526         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7527
7528         let scorer = test_utils::TestScorer::with_penalty(0);
7529         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7530         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7531         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();
7532         let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7533         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200).unwrap();
7534         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7535         check_added_monitors!(nodes[0], 1);
7536
7537         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7538         assert_eq!(events.len(), 1);
7539         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7540         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7541         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7542
7543         // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7544         // and then will wait a second random delay before failing the HTLC back:
7545         expect_pending_htlcs_forwardable!(nodes[1]);
7546         expect_pending_htlcs_forwardable!(nodes[1]);
7547
7548         // Node 3 is expecting payment of 100_000 but received 10_000,
7549         // it should fail htlc like we didn't know the preimage.
7550         nodes[1].node.process_pending_htlc_forwards();
7551
7552         let events = nodes[1].node.get_and_clear_pending_msg_events();
7553         assert_eq!(events.len(), 1);
7554         let (update_fail_htlc, commitment_signed) = match events[0] {
7555                 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 } } => {
7556                         assert!(update_add_htlcs.is_empty());
7557                         assert!(update_fulfill_htlcs.is_empty());
7558                         assert_eq!(update_fail_htlcs.len(), 1);
7559                         assert!(update_fail_malformed_htlcs.is_empty());
7560                         assert!(update_fee.is_none());
7561                         (update_fail_htlcs[0].clone(), commitment_signed)
7562                 },
7563                 _ => panic!("Unexpected event"),
7564         };
7565         check_added_monitors!(nodes[1], 1);
7566
7567         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7568         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7569
7570         // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7571         let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7572         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(CHAN_CONFIRM_DEPTH));
7573         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7574 }
7575
7576 #[test]
7577 fn test_announce_disable_channels() {
7578         // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7579         // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7580
7581         let chanmon_cfgs = create_chanmon_cfgs(2);
7582         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7583         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7584         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7585
7586         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7587         create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::known(), InitFeatures::known());
7588         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7589
7590         // Disconnect peers
7591         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7592         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7593
7594         nodes[0].node.timer_tick_occurred(); // Enabled -> DisabledStaged
7595         nodes[0].node.timer_tick_occurred(); // DisabledStaged -> Disabled
7596         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7597         assert_eq!(msg_events.len(), 3);
7598         let mut chans_disabled = HashMap::new();
7599         for e in msg_events {
7600                 match e {
7601                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7602                                 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7603                                 // Check that each channel gets updated exactly once
7604                                 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7605                                         panic!("Generated ChannelUpdate for wrong chan!");
7606                                 }
7607                         },
7608                         _ => panic!("Unexpected event"),
7609                 }
7610         }
7611         // Reconnect peers
7612         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7613         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7614         assert_eq!(reestablish_1.len(), 3);
7615         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7616         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7617         assert_eq!(reestablish_2.len(), 3);
7618
7619         // Reestablish chan_1
7620         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7621         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7622         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7623         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7624         // Reestablish chan_2
7625         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7626         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7627         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7628         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7629         // Reestablish chan_3
7630         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7631         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7632         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7633         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7634
7635         nodes[0].node.timer_tick_occurred();
7636         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7637         nodes[0].node.timer_tick_occurred();
7638         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7639         assert_eq!(msg_events.len(), 3);
7640         for e in msg_events {
7641                 match e {
7642                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7643                                 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7644                                 match chans_disabled.remove(&msg.contents.short_channel_id) {
7645                                         // Each update should have a higher timestamp than the previous one, replacing
7646                                         // the old one.
7647                                         Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7648                                         None => panic!("Generated ChannelUpdate for wrong chan!"),
7649                                 }
7650                         },
7651                         _ => panic!("Unexpected event"),
7652                 }
7653         }
7654         // Check that each channel gets updated exactly once
7655         assert!(chans_disabled.is_empty());
7656 }
7657
7658 #[test]
7659 fn test_bump_penalty_txn_on_revoked_commitment() {
7660         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7661         // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7662
7663         let chanmon_cfgs = create_chanmon_cfgs(2);
7664         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7665         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7666         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7667
7668         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7669
7670         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7671         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id())
7672                 .with_features(InvoiceFeatures::known());
7673         let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000, 30);
7674         send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7675
7676         let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7677         // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7678         assert_eq!(revoked_txn[0].output.len(), 4);
7679         assert_eq!(revoked_txn[0].input.len(), 1);
7680         assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7681         let revoked_txid = revoked_txn[0].txid();
7682
7683         let mut penalty_sum = 0;
7684         for outp in revoked_txn[0].output.iter() {
7685                 if outp.script_pubkey.is_v0_p2wsh() {
7686                         penalty_sum += outp.value;
7687                 }
7688         }
7689
7690         // Connect blocks to change height_timer range to see if we use right soonest_timelock
7691         let header_114 = connect_blocks(&nodes[1], 14);
7692
7693         // Actually revoke tx by claiming a HTLC
7694         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7695         let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7696         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] });
7697         check_added_monitors!(nodes[1], 1);
7698
7699         // One or more justice tx should have been broadcast, check it
7700         let penalty_1;
7701         let feerate_1;
7702         {
7703                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7704                 assert_eq!(node_txn.len(), 2); // justice tx (broadcasted from ChannelMonitor) + local commitment tx
7705                 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7706                 assert_eq!(node_txn[0].output.len(), 1);
7707                 check_spends!(node_txn[0], revoked_txn[0]);
7708                 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7709                 feerate_1 = fee_1 * 1000 / node_txn[0].weight() as u64;
7710                 penalty_1 = node_txn[0].txid();
7711                 node_txn.clear();
7712         };
7713
7714         // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7715         connect_blocks(&nodes[1], 15);
7716         let mut penalty_2 = penalty_1;
7717         let mut feerate_2 = 0;
7718         {
7719                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7720                 assert_eq!(node_txn.len(), 1);
7721                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7722                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7723                         assert_eq!(node_txn[0].output.len(), 1);
7724                         check_spends!(node_txn[0], revoked_txn[0]);
7725                         penalty_2 = node_txn[0].txid();
7726                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7727                         assert_ne!(penalty_2, penalty_1);
7728                         let fee_2 = penalty_sum - node_txn[0].output[0].value;
7729                         feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7730                         // Verify 25% bump heuristic
7731                         assert!(feerate_2 * 100 >= feerate_1 * 125);
7732                         node_txn.clear();
7733                 }
7734         }
7735         assert_ne!(feerate_2, 0);
7736
7737         // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7738         connect_blocks(&nodes[1], 1);
7739         let penalty_3;
7740         let mut feerate_3 = 0;
7741         {
7742                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7743                 assert_eq!(node_txn.len(), 1);
7744                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7745                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7746                         assert_eq!(node_txn[0].output.len(), 1);
7747                         check_spends!(node_txn[0], revoked_txn[0]);
7748                         penalty_3 = node_txn[0].txid();
7749                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7750                         assert_ne!(penalty_3, penalty_2);
7751                         let fee_3 = penalty_sum - node_txn[0].output[0].value;
7752                         feerate_3 = fee_3 * 1000 / node_txn[0].weight() as u64;
7753                         // Verify 25% bump heuristic
7754                         assert!(feerate_3 * 100 >= feerate_2 * 125);
7755                         node_txn.clear();
7756                 }
7757         }
7758         assert_ne!(feerate_3, 0);
7759
7760         nodes[1].node.get_and_clear_pending_events();
7761         nodes[1].node.get_and_clear_pending_msg_events();
7762 }
7763
7764 #[test]
7765 fn test_bump_penalty_txn_on_revoked_htlcs() {
7766         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7767         // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7768
7769         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7770         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7771         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7772         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7773         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7774
7775         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7776         // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7777         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7778         let scorer = test_utils::TestScorer::with_penalty(0);
7779         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7780         let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None,
7781                 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7782         let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7783         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7784         let route = get_route(&nodes[1].node.get_our_node_id(), &payment_params, &nodes[1].network_graph.read_only(), None,
7785                 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7786         send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7787
7788         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7789         assert_eq!(revoked_local_txn[0].input.len(), 1);
7790         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7791
7792         // Revoke local commitment tx
7793         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7794
7795         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7796         // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7797         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] });
7798         check_closed_broadcast!(nodes[1], true);
7799         check_added_monitors!(nodes[1], 1);
7800         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7801         connect_blocks(&nodes[1], 49); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7802
7803         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7804         assert_eq!(revoked_htlc_txn.len(), 3);
7805         check_spends!(revoked_htlc_txn[1], chan.3);
7806
7807         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7808         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7809         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7810
7811         assert_eq!(revoked_htlc_txn[2].input.len(), 1);
7812         assert_eq!(revoked_htlc_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7813         assert_eq!(revoked_htlc_txn[2].output.len(), 1);
7814         check_spends!(revoked_htlc_txn[2], revoked_local_txn[0]);
7815
7816         // Broadcast set of revoked txn on A
7817         let hash_128 = connect_blocks(&nodes[0], 40);
7818         let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7819         connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] });
7820         let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7821         connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[2].clone()] });
7822         let events = nodes[0].node.get_and_clear_pending_events();
7823         expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7824         match events[1] {
7825                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7826                 _ => panic!("Unexpected event"),
7827         }
7828         let first;
7829         let feerate_1;
7830         let penalty_txn;
7831         {
7832                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7833                 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7834                 // Verify claim tx are spending revoked HTLC txn
7835
7836                 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7837                 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7838                 // which are included in the same block (they are broadcasted because we scan the
7839                 // transactions linearly and generate claims as we go, they likely should be removed in the
7840                 // future).
7841                 assert_eq!(node_txn[0].input.len(), 1);
7842                 check_spends!(node_txn[0], revoked_local_txn[0]);
7843                 assert_eq!(node_txn[1].input.len(), 1);
7844                 check_spends!(node_txn[1], revoked_local_txn[0]);
7845                 assert_eq!(node_txn[2].input.len(), 1);
7846                 check_spends!(node_txn[2], revoked_local_txn[0]);
7847
7848                 // Each of the three justice transactions claim a separate (single) output of the three
7849                 // available, which we check here:
7850                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7851                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7852                 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7853
7854                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7855                 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7856
7857                 // node_txn[3] is the local commitment tx broadcast just because (and somewhat in case of
7858                 // reorgs, though its not clear its ever worth broadcasting conflicting txn like this when
7859                 // a remote commitment tx has already been confirmed).
7860                 check_spends!(node_txn[3], chan.3);
7861
7862                 // node_txn[4] spends the revoked outputs from the revoked_htlc_txn (which only have one
7863                 // output, checked above).
7864                 assert_eq!(node_txn[4].input.len(), 2);
7865                 assert_eq!(node_txn[4].output.len(), 1);
7866                 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7867
7868                 first = node_txn[4].txid();
7869                 // Store both feerates for later comparison
7870                 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[4].output[0].value;
7871                 feerate_1 = fee_1 * 1000 / node_txn[4].weight() as u64;
7872                 penalty_txn = vec![node_txn[2].clone()];
7873                 node_txn.clear();
7874         }
7875
7876         // Connect one more block to see if bumped penalty are issued for HTLC txn
7877         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7878         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7879         let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7880         connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() });
7881         {
7882                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7883                 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7884
7885                 check_spends!(node_txn[0], revoked_local_txn[0]);
7886                 check_spends!(node_txn[1], revoked_local_txn[0]);
7887                 // Note that these are both bogus - they spend outputs already claimed in block 129:
7888                 if node_txn[0].input[0].previous_output == revoked_htlc_txn[0].input[0].previous_output  {
7889                         assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7890                 } else {
7891                         assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7892                         assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7893                 }
7894
7895                 node_txn.clear();
7896         };
7897
7898         // Few more blocks to confirm penalty txn
7899         connect_blocks(&nodes[0], 4);
7900         assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7901         let header_144 = connect_blocks(&nodes[0], 9);
7902         let node_txn = {
7903                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7904                 assert_eq!(node_txn.len(), 1);
7905
7906                 assert_eq!(node_txn[0].input.len(), 2);
7907                 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7908                 // Verify bumped tx is different and 25% bump heuristic
7909                 assert_ne!(first, node_txn[0].txid());
7910                 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[0].output[0].value;
7911                 let feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7912                 assert!(feerate_2 * 100 > feerate_1 * 125);
7913                 let txn = vec![node_txn[0].clone()];
7914                 node_txn.clear();
7915                 txn
7916         };
7917         // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7918         let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7919         connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn });
7920         connect_blocks(&nodes[0], 20);
7921         {
7922                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7923                 // We verify than no new transaction has been broadcast because previously
7924                 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7925                 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7926                 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7927                 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7928                 // up bumped justice generation.
7929                 assert_eq!(node_txn.len(), 0);
7930                 node_txn.clear();
7931         }
7932         check_closed_broadcast!(nodes[0], true);
7933         check_added_monitors!(nodes[0], 1);
7934 }
7935
7936 #[test]
7937 fn test_bump_penalty_txn_on_remote_commitment() {
7938         // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7939         // we're able to claim outputs on remote commitment transaction before timelocks expiration
7940
7941         // Create 2 HTLCs
7942         // Provide preimage for one
7943         // Check aggregation
7944
7945         let chanmon_cfgs = create_chanmon_cfgs(2);
7946         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7947         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7948         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7949
7950         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7951         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7952         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7953
7954         // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7955         let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7956         assert_eq!(remote_txn[0].output.len(), 4);
7957         assert_eq!(remote_txn[0].input.len(), 1);
7958         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7959
7960         // Claim a HTLC without revocation (provide B monitor with preimage)
7961         nodes[1].node.claim_funds(payment_preimage);
7962         mine_transaction(&nodes[1], &remote_txn[0]);
7963         check_added_monitors!(nodes[1], 2);
7964         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7965
7966         // One or more claim tx should have been broadcast, check it
7967         let timeout;
7968         let preimage;
7969         let preimage_bump;
7970         let feerate_timeout;
7971         let feerate_preimage;
7972         {
7973                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7974                 // 9 transactions including:
7975                 // 1*2 ChannelManager local broadcasts of commitment + HTLC-Success
7976                 // 1*3 ChannelManager local broadcasts of commitment + HTLC-Success + HTLC-Timeout
7977                 // 2 * HTLC-Success (one RBF bump we'll check later)
7978                 // 1 * HTLC-Timeout
7979                 assert_eq!(node_txn.len(), 8);
7980                 assert_eq!(node_txn[0].input.len(), 1);
7981                 assert_eq!(node_txn[6].input.len(), 1);
7982                 check_spends!(node_txn[0], remote_txn[0]);
7983                 check_spends!(node_txn[6], remote_txn[0]);
7984
7985                 check_spends!(node_txn[1], chan.3);
7986                 check_spends!(node_txn[2], node_txn[1]);
7987
7988                 if node_txn[0].input[0].previous_output == node_txn[3].input[0].previous_output {
7989                         preimage_bump = node_txn[3].clone();
7990                         check_spends!(node_txn[3], remote_txn[0]);
7991
7992                         assert_eq!(node_txn[1], node_txn[4]);
7993                         assert_eq!(node_txn[2], node_txn[5]);
7994                 } else {
7995                         preimage_bump = node_txn[7].clone();
7996                         check_spends!(node_txn[7], remote_txn[0]);
7997                         assert_eq!(node_txn[0].input[0].previous_output, node_txn[7].input[0].previous_output);
7998
7999                         assert_eq!(node_txn[1], node_txn[3]);
8000                         assert_eq!(node_txn[2], node_txn[4]);
8001                 }
8002
8003                 timeout = node_txn[6].txid();
8004                 let index = node_txn[6].input[0].previous_output.vout;
8005                 let fee = remote_txn[0].output[index as usize].value - node_txn[6].output[0].value;
8006                 feerate_timeout = fee * 1000 / node_txn[6].weight() as u64;
8007
8008                 preimage = node_txn[0].txid();
8009                 let index = node_txn[0].input[0].previous_output.vout;
8010                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8011                 feerate_preimage = fee * 1000 / node_txn[0].weight() as u64;
8012
8013                 node_txn.clear();
8014         };
8015         assert_ne!(feerate_timeout, 0);
8016         assert_ne!(feerate_preimage, 0);
8017
8018         // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
8019         connect_blocks(&nodes[1], 15);
8020         {
8021                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8022                 assert_eq!(node_txn.len(), 1);
8023                 assert_eq!(node_txn[0].input.len(), 1);
8024                 assert_eq!(preimage_bump.input.len(), 1);
8025                 check_spends!(node_txn[0], remote_txn[0]);
8026                 check_spends!(preimage_bump, remote_txn[0]);
8027
8028                 let index = preimage_bump.input[0].previous_output.vout;
8029                 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
8030                 let new_feerate = fee * 1000 / preimage_bump.weight() as u64;
8031                 assert!(new_feerate * 100 > feerate_timeout * 125);
8032                 assert_ne!(timeout, preimage_bump.txid());
8033
8034                 let index = node_txn[0].input[0].previous_output.vout;
8035                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8036                 let new_feerate = fee * 1000 / node_txn[0].weight() as u64;
8037                 assert!(new_feerate * 100 > feerate_preimage * 125);
8038                 assert_ne!(preimage, node_txn[0].txid());
8039
8040                 node_txn.clear();
8041         }
8042
8043         nodes[1].node.get_and_clear_pending_events();
8044         nodes[1].node.get_and_clear_pending_msg_events();
8045 }
8046
8047 #[test]
8048 fn test_counterparty_raa_skip_no_crash() {
8049         // Previously, if our counterparty sent two RAAs in a row without us having provided a
8050         // commitment transaction, we would have happily carried on and provided them the next
8051         // commitment transaction based on one RAA forward. This would probably eventually have led to
8052         // channel closure, but it would not have resulted in funds loss. Still, our
8053         // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
8054         // check simply that the channel is closed in response to such an RAA, but don't check whether
8055         // we decide to punish our counterparty for revoking their funds (as we don't currently
8056         // implement that).
8057         let chanmon_cfgs = create_chanmon_cfgs(2);
8058         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8059         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8060         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8061         let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
8062
8063         let mut guard = nodes[0].node.channel_state.lock().unwrap();
8064         let keys = guard.by_id.get_mut(&channel_id).unwrap().get_signer();
8065
8066         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
8067
8068         // Make signer believe we got a counterparty signature, so that it allows the revocation
8069         keys.get_enforcement_state().last_holder_commitment -= 1;
8070         let per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
8071
8072         // Must revoke without gaps
8073         keys.get_enforcement_state().last_holder_commitment -= 1;
8074         keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
8075
8076         keys.get_enforcement_state().last_holder_commitment -= 1;
8077         let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
8078                 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
8079
8080         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
8081                 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
8082         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
8083         check_added_monitors!(nodes[1], 1);
8084         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
8085 }
8086
8087 #[test]
8088 fn test_bump_txn_sanitize_tracking_maps() {
8089         // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
8090         // verify we clean then right after expiration of ANTI_REORG_DELAY.
8091
8092         let chanmon_cfgs = create_chanmon_cfgs(2);
8093         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8094         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8095         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8096
8097         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8098         // Lock HTLC in both directions
8099         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8100         route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
8101
8102         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
8103         assert_eq!(revoked_local_txn[0].input.len(), 1);
8104         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8105
8106         // Revoke local commitment tx
8107         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
8108
8109         // Broadcast set of revoked txn on A
8110         connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
8111         expect_pending_htlcs_forwardable_ignore!(nodes[0]);
8112         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
8113
8114         mine_transaction(&nodes[0], &revoked_local_txn[0]);
8115         check_closed_broadcast!(nodes[0], true);
8116         check_added_monitors!(nodes[0], 1);
8117         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8118         let penalty_txn = {
8119                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8120                 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
8121                 check_spends!(node_txn[0], revoked_local_txn[0]);
8122                 check_spends!(node_txn[1], revoked_local_txn[0]);
8123                 check_spends!(node_txn[2], revoked_local_txn[0]);
8124                 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
8125                 node_txn.clear();
8126                 penalty_txn
8127         };
8128         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8129         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
8130         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8131         {
8132                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
8133                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
8134                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
8135         }
8136 }
8137
8138 #[test]
8139 fn test_pending_claimed_htlc_no_balance_underflow() {
8140         // Tests that if we have a pending outbound HTLC as well as a claimed-but-not-fully-removed
8141         // HTLC we will not underflow when we call `Channel::get_balance_msat()`.
8142         let chanmon_cfgs = create_chanmon_cfgs(2);
8143         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8144         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8145         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8146         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
8147
8148         let payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 1_010_000).0;
8149         nodes[1].node.claim_funds(payment_preimage);
8150         check_added_monitors!(nodes[1], 1);
8151         let fulfill_ev = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8152
8153         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &fulfill_ev.update_fulfill_htlcs[0]);
8154         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
8155         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &fulfill_ev.commitment_signed);
8156         check_added_monitors!(nodes[0], 1);
8157         let (_raa, _cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
8158
8159         // At this point nodes[1] has received 1,010k msat (10k msat more than their reserve) and can
8160         // send an HTLC back (though it will go in the holding cell). Send an HTLC back and check we
8161         // can get our balance.
8162
8163         // Get a route from nodes[1] to nodes[0] by getting a route going the other way and then flip
8164         // the public key of the only hop. This works around ChannelDetails not showing the
8165         // almost-claimed HTLC as available balance.
8166         let (mut route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 10_000);
8167         route.payment_params = None; // This is all wrong, but unnecessary
8168         route.paths[0][0].pubkey = nodes[0].node.get_our_node_id();
8169         let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[0]);
8170         nodes[1].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
8171
8172         assert_eq!(nodes[1].node.list_channels()[0].balance_msat, 1_000_000);
8173 }
8174
8175 #[test]
8176 fn test_channel_conf_timeout() {
8177         // Tests that, for inbound channels, we give up on them if the funding transaction does not
8178         // confirm within 2016 blocks, as recommended by BOLT 2.
8179         let chanmon_cfgs = create_chanmon_cfgs(2);
8180         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8181         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8182         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8183
8184         let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000, InitFeatures::known(), InitFeatures::known());
8185
8186         // The outbound node should wait forever for confirmation:
8187         // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
8188         // copied here instead of directly referencing the constant.
8189         connect_blocks(&nodes[0], 2016);
8190         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8191
8192         // The inbound node should fail the channel after exactly 2016 blocks
8193         connect_blocks(&nodes[1], 2015);
8194         check_added_monitors!(nodes[1], 0);
8195         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8196
8197         connect_blocks(&nodes[1], 1);
8198         check_added_monitors!(nodes[1], 1);
8199         check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut);
8200         let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
8201         assert_eq!(close_ev.len(), 1);
8202         match close_ev[0] {
8203                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
8204                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8205                         assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
8206                 },
8207                 _ => panic!("Unexpected event"),
8208         }
8209 }
8210
8211 #[test]
8212 fn test_override_channel_config() {
8213         let chanmon_cfgs = create_chanmon_cfgs(2);
8214         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8215         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8216         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8217
8218         // Node0 initiates a channel to node1 using the override config.
8219         let mut override_config = UserConfig::default();
8220         override_config.own_channel_config.our_to_self_delay = 200;
8221
8222         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
8223
8224         // Assert the channel created by node0 is using the override config.
8225         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8226         assert_eq!(res.channel_flags, 0);
8227         assert_eq!(res.to_self_delay, 200);
8228 }
8229
8230 #[test]
8231 fn test_override_0msat_htlc_minimum() {
8232         let mut zero_config = UserConfig::default();
8233         zero_config.own_channel_config.our_htlc_minimum_msat = 0;
8234         let chanmon_cfgs = create_chanmon_cfgs(2);
8235         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8236         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
8237         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8238
8239         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
8240         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8241         assert_eq!(res.htlc_minimum_msat, 1);
8242
8243         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8244         let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8245         assert_eq!(res.htlc_minimum_msat, 1);
8246 }
8247
8248 #[test]
8249 fn test_channel_update_has_correct_htlc_maximum_msat() {
8250         // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
8251         // Bolt 7 specifies that if present `htlc_maximum_msat`:
8252         // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
8253         // 90% of the `channel_value`.
8254         // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
8255
8256         let mut config_30_percent = UserConfig::default();
8257         config_30_percent.channel_options.announced_channel = true;
8258         config_30_percent.own_channel_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
8259         let mut config_50_percent = UserConfig::default();
8260         config_50_percent.channel_options.announced_channel = true;
8261         config_50_percent.own_channel_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
8262         let mut config_95_percent = UserConfig::default();
8263         config_95_percent.channel_options.announced_channel = true;
8264         config_95_percent.own_channel_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
8265         let mut config_100_percent = UserConfig::default();
8266         config_100_percent.channel_options.announced_channel = true;
8267         config_100_percent.own_channel_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
8268
8269         let chanmon_cfgs = create_chanmon_cfgs(4);
8270         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8271         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)]);
8272         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8273
8274         let channel_value_satoshis = 100000;
8275         let channel_value_msat = channel_value_satoshis * 1000;
8276         let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
8277         let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
8278         let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
8279
8280         let (node_0_chan_update, node_1_chan_update, _, _)  = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value_satoshis, 10001, InitFeatures::known(), InitFeatures::known());
8281         let (node_2_chan_update, node_3_chan_update, _, _)  = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, channel_value_satoshis, 10001, InitFeatures::known(), InitFeatures::known());
8282
8283         // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
8284         // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
8285         assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, OptionalField::Present(channel_value_50_percent_msat));
8286         // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
8287         // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
8288         assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, OptionalField::Present(channel_value_30_percent_msat));
8289
8290         // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
8291         // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
8292         // `channel_value`.
8293         assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, OptionalField::Present(channel_value_90_percent_msat));
8294         // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
8295         // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
8296         // `channel_value`.
8297         assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, OptionalField::Present(channel_value_90_percent_msat));
8298 }
8299
8300 #[test]
8301 fn test_manually_accept_inbound_channel_request() {
8302         let mut manually_accept_conf = UserConfig::default();
8303         manually_accept_conf.manually_accept_inbound_channels = true;
8304         let chanmon_cfgs = create_chanmon_cfgs(2);
8305         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8306         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8307         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8308
8309         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8310         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8311
8312         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8313
8314         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8315         // accepting the inbound channel request.
8316         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8317
8318         let events = nodes[1].node.get_and_clear_pending_events();
8319         match events[0] {
8320                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8321                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, 23).unwrap();
8322                 }
8323                 _ => panic!("Unexpected event"),
8324         }
8325
8326         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8327         assert_eq!(accept_msg_ev.len(), 1);
8328
8329         match accept_msg_ev[0] {
8330                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8331                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8332                 }
8333                 _ => panic!("Unexpected event"),
8334         }
8335
8336         nodes[1].node.force_close_channel(&temp_channel_id).unwrap();
8337
8338         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8339         assert_eq!(close_msg_ev.len(), 1);
8340
8341         let events = nodes[1].node.get_and_clear_pending_events();
8342         match events[0] {
8343                 Event::ChannelClosed { user_channel_id, .. } => {
8344                         assert_eq!(user_channel_id, 23);
8345                 }
8346                 _ => panic!("Unexpected event"),
8347         }
8348 }
8349
8350 #[test]
8351 fn test_manually_reject_inbound_channel_request() {
8352         let mut manually_accept_conf = UserConfig::default();
8353         manually_accept_conf.manually_accept_inbound_channels = true;
8354         let chanmon_cfgs = create_chanmon_cfgs(2);
8355         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8356         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8357         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8358
8359         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8360         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8361
8362         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8363
8364         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8365         // rejecting the inbound channel request.
8366         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8367
8368         let events = nodes[1].node.get_and_clear_pending_events();
8369         match events[0] {
8370                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8371                         nodes[1].node.force_close_channel(&temporary_channel_id).unwrap();
8372                 }
8373                 _ => panic!("Unexpected event"),
8374         }
8375
8376         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8377         assert_eq!(close_msg_ev.len(), 1);
8378
8379         match close_msg_ev[0] {
8380                 MessageSendEvent::HandleError { ref node_id, .. } => {
8381                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8382                 }
8383                 _ => panic!("Unexpected event"),
8384         }
8385         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
8386 }
8387
8388 #[test]
8389 fn test_reject_funding_before_inbound_channel_accepted() {
8390         // This tests that when `UserConfig::manually_accept_inbound_channels` is set to true, inbound
8391         // channels must to be manually accepted through `ChannelManager::accept_inbound_channel` by
8392         // the node operator before the counterparty sends a `FundingCreated` message. If a
8393         // `FundingCreated` message is received before the channel is accepted, it should be rejected
8394         // and the channel should be closed.
8395         let mut manually_accept_conf = UserConfig::default();
8396         manually_accept_conf.manually_accept_inbound_channels = true;
8397         let chanmon_cfgs = create_chanmon_cfgs(2);
8398         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8399         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8400         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8401
8402         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8403         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8404         let temp_channel_id = res.temporary_channel_id;
8405
8406         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8407
8408         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in the `msg_events`.
8409         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8410
8411         // Clear the `Event::OpenChannelRequest` event without responding to the request.
8412         nodes[1].node.get_and_clear_pending_events();
8413
8414         // Get the `AcceptChannel` message of `nodes[1]` without calling
8415         // `ChannelManager::accept_inbound_channel`, which generates a
8416         // `MessageSendEvent::SendAcceptChannel` event. The message is passed to `nodes[0]`
8417         // `handle_accept_channel`, which is required in order for `create_funding_transaction` to
8418         // succeed when `nodes[0]` is passed to it.
8419         {
8420                 let mut lock;
8421                 let channel = get_channel_ref!(&nodes[1], lock, temp_channel_id);
8422                 let accept_chan_msg = channel.get_accept_channel_message();
8423                 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8424         }
8425
8426         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], 100000, 42);
8427
8428         nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
8429         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8430
8431         // The `funding_created_msg` should be rejected by `nodes[1]` as it hasn't accepted the channel
8432         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8433
8434         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8435         assert_eq!(close_msg_ev.len(), 1);
8436
8437         let expected_err = "FundingCreated message received before the channel was accepted";
8438         match close_msg_ev[0] {
8439                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id, } => {
8440                         assert_eq!(msg.channel_id, temp_channel_id);
8441                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8442                         assert_eq!(msg.data, expected_err);
8443                 }
8444                 _ => panic!("Unexpected event"),
8445         }
8446
8447         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
8448 }
8449
8450 #[test]
8451 fn test_can_not_accept_inbound_channel_twice() {
8452         let mut manually_accept_conf = UserConfig::default();
8453         manually_accept_conf.manually_accept_inbound_channels = true;
8454         let chanmon_cfgs = create_chanmon_cfgs(2);
8455         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8456         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8457         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8458
8459         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8460         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8461
8462         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8463
8464         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8465         // accepting the inbound channel request.
8466         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8467
8468         let events = nodes[1].node.get_and_clear_pending_events();
8469         match events[0] {
8470                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8471                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, 0).unwrap();
8472                         let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, 0);
8473                         match api_res {
8474                                 Err(APIError::APIMisuseError { err }) => {
8475                                         assert_eq!(err, "The channel isn't currently awaiting to be accepted.");
8476                                 },
8477                                 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
8478                                 Err(_) => panic!("Unexpected Error"),
8479                         }
8480                 }
8481                 _ => panic!("Unexpected event"),
8482         }
8483
8484         // Ensure that the channel wasn't closed after attempting to accept it twice.
8485         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8486         assert_eq!(accept_msg_ev.len(), 1);
8487
8488         match accept_msg_ev[0] {
8489                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8490                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8491                 }
8492                 _ => panic!("Unexpected event"),
8493         }
8494 }
8495
8496 #[test]
8497 fn test_can_not_accept_unknown_inbound_channel() {
8498         let chanmon_cfg = create_chanmon_cfgs(1);
8499         let node_cfg = create_node_cfgs(1, &chanmon_cfg);
8500         let node_chanmgr = create_node_chanmgrs(1, &node_cfg, &[None]);
8501         let node = create_network(1, &node_cfg, &node_chanmgr)[0].node;
8502
8503         let unknown_channel_id = [0; 32];
8504         let api_res = node.accept_inbound_channel(&unknown_channel_id, 0);
8505         match api_res {
8506                 Err(APIError::ChannelUnavailable { err }) => {
8507                         assert_eq!(err, "Can't accept a channel that doesn't exist");
8508                 },
8509                 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
8510                 Err(_) => panic!("Unexpected Error"),
8511         }
8512 }
8513
8514 #[test]
8515 fn test_simple_mpp() {
8516         // Simple test of sending a multi-path payment.
8517         let chanmon_cfgs = create_chanmon_cfgs(4);
8518         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8519         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8520         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8521
8522         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8523         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8524         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8525         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8526
8527         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8528         let path = route.paths[0].clone();
8529         route.paths.push(path);
8530         route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8531         route.paths[0][0].short_channel_id = chan_1_id;
8532         route.paths[0][1].short_channel_id = chan_3_id;
8533         route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8534         route.paths[1][0].short_channel_id = chan_2_id;
8535         route.paths[1][1].short_channel_id = chan_4_id;
8536         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8537         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8538 }
8539
8540 #[test]
8541 fn test_preimage_storage() {
8542         // Simple test of payment preimage storage allowing no client-side storage to claim payments
8543         let chanmon_cfgs = create_chanmon_cfgs(2);
8544         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8545         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8546         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8547
8548         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8549
8550         {
8551                 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200).unwrap();
8552                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8553                 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8554                 check_added_monitors!(nodes[0], 1);
8555                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8556                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8557                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8558                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8559         }
8560         // Note that after leaving the above scope we have no knowledge of any arguments or return
8561         // values from previous calls.
8562         expect_pending_htlcs_forwardable!(nodes[1]);
8563         let events = nodes[1].node.get_and_clear_pending_events();
8564         assert_eq!(events.len(), 1);
8565         match events[0] {
8566                 Event::PaymentReceived { ref purpose, .. } => {
8567                         match &purpose {
8568                                 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
8569                                         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8570                                 },
8571                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
8572                         }
8573                 },
8574                 _ => panic!("Unexpected event"),
8575         }
8576 }
8577
8578 #[test]
8579 #[allow(deprecated)]
8580 fn test_secret_timeout() {
8581         // Simple test of payment secret storage time outs. After
8582         // `create_inbound_payment(_for_hash)_legacy` is removed, this test will be removed as well.
8583         let chanmon_cfgs = create_chanmon_cfgs(2);
8584         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8585         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8586         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8587
8588         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8589
8590         let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment_legacy(Some(100_000), 2).unwrap();
8591
8592         // We should fail to register the same payment hash twice, at least until we've connected a
8593         // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
8594         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8595                 assert_eq!(err, "Duplicate payment hash");
8596         } else { panic!(); }
8597         let mut block = {
8598                 let node_1_blocks = nodes[1].blocks.lock().unwrap();
8599                 Block {
8600                         header: BlockHeader {
8601                                 version: 0x2000000,
8602                                 prev_blockhash: node_1_blocks.last().unwrap().0.block_hash(),
8603                                 merkle_root: Default::default(),
8604                                 time: node_1_blocks.len() as u32 + 7200, bits: 42, nonce: 42 },
8605                         txdata: vec![],
8606                 }
8607         };
8608         connect_block(&nodes[1], &block);
8609         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8610                 assert_eq!(err, "Duplicate payment hash");
8611         } else { panic!(); }
8612
8613         // If we then connect the second block, we should be able to register the same payment hash
8614         // again (this time getting a new payment secret).
8615         block.header.prev_blockhash = block.header.block_hash();
8616         block.header.time += 1;
8617         connect_block(&nodes[1], &block);
8618         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2).unwrap();
8619         assert_ne!(payment_secret_1, our_payment_secret);
8620
8621         {
8622                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8623                 nodes[0].node.send_payment(&route, payment_hash, &Some(our_payment_secret)).unwrap();
8624                 check_added_monitors!(nodes[0], 1);
8625                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8626                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8627                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8628                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8629         }
8630         // Note that after leaving the above scope we have no knowledge of any arguments or return
8631         // values from previous calls.
8632         expect_pending_htlcs_forwardable!(nodes[1]);
8633         let events = nodes[1].node.get_and_clear_pending_events();
8634         assert_eq!(events.len(), 1);
8635         match events[0] {
8636                 Event::PaymentReceived { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret }, .. } => {
8637                         assert!(payment_preimage.is_none());
8638                         assert_eq!(payment_secret, our_payment_secret);
8639                         // We don't actually have the payment preimage with which to claim this payment!
8640                 },
8641                 _ => panic!("Unexpected event"),
8642         }
8643 }
8644
8645 #[test]
8646 fn test_bad_secret_hash() {
8647         // Simple test of unregistered payment hash/invalid payment secret handling
8648         let chanmon_cfgs = create_chanmon_cfgs(2);
8649         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8650         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8651         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8652
8653         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8654
8655         let random_payment_hash = PaymentHash([42; 32]);
8656         let random_payment_secret = PaymentSecret([43; 32]);
8657         let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2).unwrap();
8658         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8659
8660         // All the below cases should end up being handled exactly identically, so we macro the
8661         // resulting events.
8662         macro_rules! handle_unknown_invalid_payment_data {
8663                 () => {
8664                         check_added_monitors!(nodes[0], 1);
8665                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8666                         let payment_event = SendEvent::from_event(events.pop().unwrap());
8667                         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8668                         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8669
8670                         // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8671                         // again to process the pending backwards-failure of the HTLC
8672                         expect_pending_htlcs_forwardable!(nodes[1]);
8673                         expect_pending_htlcs_forwardable!(nodes[1]);
8674                         check_added_monitors!(nodes[1], 1);
8675
8676                         // We should fail the payment back
8677                         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8678                         match events.pop().unwrap() {
8679                                 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8680                                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8681                                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8682                                 },
8683                                 _ => panic!("Unexpected event"),
8684                         }
8685                 }
8686         }
8687
8688         let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8689         // Error data is the HTLC value (100,000) and current block height
8690         let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8691
8692         // Send a payment with the right payment hash but the wrong payment secret
8693         nodes[0].node.send_payment(&route, our_payment_hash, &Some(random_payment_secret)).unwrap();
8694         handle_unknown_invalid_payment_data!();
8695         expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8696
8697         // Send a payment with a random payment hash, but the right payment secret
8698         nodes[0].node.send_payment(&route, random_payment_hash, &Some(our_payment_secret)).unwrap();
8699         handle_unknown_invalid_payment_data!();
8700         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8701
8702         // Send a payment with a random payment hash and random payment secret
8703         nodes[0].node.send_payment(&route, random_payment_hash, &Some(random_payment_secret)).unwrap();
8704         handle_unknown_invalid_payment_data!();
8705         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8706 }
8707
8708 #[test]
8709 fn test_update_err_monitor_lockdown() {
8710         // Our monitor will lock update of local commitment transaction if a broadcastion condition
8711         // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8712         // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
8713         //
8714         // This scenario may happen in a watchtower setup, where watchtower process a block height
8715         // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8716         // commitment at same time.
8717
8718         let chanmon_cfgs = create_chanmon_cfgs(2);
8719         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8720         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8721         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8722
8723         // Create some initial channel
8724         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8725         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8726
8727         // Rebalance the network to generate htlc in the two directions
8728         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8729
8730         // Route a HTLC from node 0 to node 1 (but don't settle)
8731         let preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8732
8733         // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8734         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8735         let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8736         let persister = test_utils::TestPersister::new();
8737         let watchtower = {
8738                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8739                 let mut w = test_utils::TestVecWriter(Vec::new());
8740                 monitor.write(&mut w).unwrap();
8741                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8742                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8743                 assert!(new_monitor == *monitor);
8744                 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);
8745                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8746                 watchtower
8747         };
8748         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8749         let block = Block { header, txdata: vec![] };
8750         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8751         // transaction lock time requirements here.
8752         chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 0));
8753         watchtower.chain_monitor.block_connected(&block, 200);
8754
8755         // Try to update ChannelMonitor
8756         assert!(nodes[1].node.claim_funds(preimage));
8757         check_added_monitors!(nodes[1], 1);
8758         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8759         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8760         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8761         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8762                 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8763                         if let Err(_) =  watchtower.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8764                         if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8765                 } else { assert!(false); }
8766         } else { assert!(false); };
8767         // Our local monitor is in-sync and hasn't processed yet timeout
8768         check_added_monitors!(nodes[0], 1);
8769         let events = nodes[0].node.get_and_clear_pending_events();
8770         assert_eq!(events.len(), 1);
8771 }
8772
8773 #[test]
8774 fn test_concurrent_monitor_claim() {
8775         // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8776         // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8777         // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8778         // state N+1 confirms. Alice claims output from state N+1.
8779
8780         let chanmon_cfgs = create_chanmon_cfgs(2);
8781         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8782         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8783         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8784
8785         // Create some initial channel
8786         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8787         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8788
8789         // Rebalance the network to generate htlc in the two directions
8790         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8791
8792         // Route a HTLC from node 0 to node 1 (but don't settle)
8793         route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8794
8795         // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8796         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8797         let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8798         let persister = test_utils::TestPersister::new();
8799         let watchtower_alice = {
8800                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8801                 let mut w = test_utils::TestVecWriter(Vec::new());
8802                 monitor.write(&mut w).unwrap();
8803                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8804                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8805                 assert!(new_monitor == *monitor);
8806                 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);
8807                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8808                 watchtower
8809         };
8810         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8811         let block = Block { header, txdata: vec![] };
8812         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8813         // transaction lock time requirements here.
8814         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));
8815         watchtower_alice.chain_monitor.block_connected(&block, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8816
8817         // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8818         {
8819                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8820                 assert_eq!(txn.len(), 2);
8821                 txn.clear();
8822         }
8823
8824         // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8825         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8826         let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8827         let persister = test_utils::TestPersister::new();
8828         let watchtower_bob = {
8829                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8830                 let mut w = test_utils::TestVecWriter(Vec::new());
8831                 monitor.write(&mut w).unwrap();
8832                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8833                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8834                 assert!(new_monitor == *monitor);
8835                 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);
8836                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8837                 watchtower
8838         };
8839         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8840         watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8841
8842         // Route another payment to generate another update with still previous HTLC pending
8843         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8844         {
8845                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8846         }
8847         check_added_monitors!(nodes[1], 1);
8848
8849         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8850         assert_eq!(updates.update_add_htlcs.len(), 1);
8851         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8852         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8853                 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8854                         // Watchtower Alice should already have seen the block and reject the update
8855                         if let Err(_) =  watchtower_alice.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8856                         if let Ok(_) = watchtower_bob.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8857                         if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8858                 } else { assert!(false); }
8859         } else { assert!(false); };
8860         // Our local monitor is in-sync and hasn't processed yet timeout
8861         check_added_monitors!(nodes[0], 1);
8862
8863         //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8864         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8865         watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8866
8867         // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8868         let bob_state_y;
8869         {
8870                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8871                 assert_eq!(txn.len(), 2);
8872                 bob_state_y = txn[0].clone();
8873                 txn.clear();
8874         };
8875
8876         // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8877         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8878         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);
8879         {
8880                 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8881                 // We broadcast twice the transaction, once due to the HTLC-timeout, once due
8882                 // the onchain detection of the HTLC output
8883                 assert_eq!(htlc_txn.len(), 2);
8884                 check_spends!(htlc_txn[0], bob_state_y);
8885                 check_spends!(htlc_txn[1], bob_state_y);
8886         }
8887 }
8888
8889 #[test]
8890 fn test_pre_lockin_no_chan_closed_update() {
8891         // Test that if a peer closes a channel in response to a funding_created message we don't
8892         // generate a channel update (as the channel cannot appear on chain without a funding_signed
8893         // message).
8894         //
8895         // Doing so would imply a channel monitor update before the initial channel monitor
8896         // registration, violating our API guarantees.
8897         //
8898         // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8899         // then opening a second channel with the same funding output as the first (which is not
8900         // rejected because the first channel does not exist in the ChannelManager) and closing it
8901         // before receiving funding_signed.
8902         let chanmon_cfgs = create_chanmon_cfgs(2);
8903         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8904         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8905         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8906
8907         // Create an initial channel
8908         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8909         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8910         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8911         let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8912         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8913
8914         // Move the first channel through the funding flow...
8915         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], 100000, 42);
8916
8917         nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
8918         check_added_monitors!(nodes[0], 0);
8919
8920         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8921         let channel_id = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8922         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8923         assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8924         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "Hi".to_string() }, true);
8925 }
8926
8927 #[test]
8928 fn test_htlc_no_detection() {
8929         // This test is a mutation to underscore the detection logic bug we had
8930         // before #653. HTLC value routed is above the remaining balance, thus
8931         // inverting HTLC and `to_remote` output. HTLC will come second and
8932         // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8933         // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8934         // outputs order detection for correct spending children filtring.
8935
8936         let chanmon_cfgs = create_chanmon_cfgs(2);
8937         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8938         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8939         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8940
8941         // Create some initial channels
8942         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8943
8944         send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8945         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8946         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8947         assert_eq!(local_txn[0].input.len(), 1);
8948         assert_eq!(local_txn[0].output.len(), 3);
8949         check_spends!(local_txn[0], chan_1.3);
8950
8951         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8952         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8953         connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] });
8954         // We deliberately connect the local tx twice as this should provoke a failure calling
8955         // this test before #653 fix.
8956         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);
8957         check_closed_broadcast!(nodes[0], true);
8958         check_added_monitors!(nodes[0], 1);
8959         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8960         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1);
8961
8962         let htlc_timeout = {
8963                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8964                 assert_eq!(node_txn[1].input.len(), 1);
8965                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8966                 check_spends!(node_txn[1], local_txn[0]);
8967                 node_txn[1].clone()
8968         };
8969
8970         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8971         connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] });
8972         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8973         expect_payment_failed!(nodes[0], our_payment_hash, true);
8974 }
8975
8976 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8977         // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8978         // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8979         // Carol, Alice would be the upstream node, and Carol the downstream.)
8980         //
8981         // Steps of the test:
8982         // 1) Alice sends a HTLC to Carol through Bob.
8983         // 2) Carol doesn't settle the HTLC.
8984         // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8985         // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8986         // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8987         //    but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8988         // 5) Carol release the preimage to Bob off-chain.
8989         // 6) Bob claims the offered output on the broadcasted commitment.
8990         let chanmon_cfgs = create_chanmon_cfgs(3);
8991         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8992         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8993         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8994
8995         // Create some initial channels
8996         let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8997         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8998
8999         // Steps (1) and (2):
9000         // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
9001         let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3_000_000);
9002
9003         // Check that Alice's commitment transaction now contains an output for this HTLC.
9004         let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
9005         check_spends!(alice_txn[0], chan_ab.3);
9006         assert_eq!(alice_txn[0].output.len(), 2);
9007         check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
9008         assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9009         assert_eq!(alice_txn.len(), 2);
9010
9011         // Steps (3) and (4):
9012         // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
9013         // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
9014         let mut force_closing_node = 0; // Alice force-closes
9015         if !broadcast_alice { force_closing_node = 1; } // Bob force-closes
9016         nodes[force_closing_node].node.force_close_channel(&chan_ab.2).unwrap();
9017         check_closed_broadcast!(nodes[force_closing_node], true);
9018         check_added_monitors!(nodes[force_closing_node], 1);
9019         check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
9020         if go_onchain_before_fulfill {
9021                 let txn_to_broadcast = match broadcast_alice {
9022                         true => alice_txn.clone(),
9023                         false => get_local_commitment_txn!(nodes[1], chan_ab.2)
9024                 };
9025                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
9026                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
9027                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
9028                 if broadcast_alice {
9029                         check_closed_broadcast!(nodes[1], true);
9030                         check_added_monitors!(nodes[1], 1);
9031                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
9032                 }
9033                 assert_eq!(bob_txn.len(), 1);
9034                 check_spends!(bob_txn[0], chan_ab.3);
9035         }
9036
9037         // Step (5):
9038         // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
9039         // process of removing the HTLC from their commitment transactions.
9040         assert!(nodes[2].node.claim_funds(payment_preimage));
9041         check_added_monitors!(nodes[2], 1);
9042         let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
9043         assert!(carol_updates.update_add_htlcs.is_empty());
9044         assert!(carol_updates.update_fail_htlcs.is_empty());
9045         assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
9046         assert!(carol_updates.update_fee.is_none());
9047         assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
9048
9049         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
9050         expect_payment_forwarded!(nodes[1], nodes[0], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false);
9051         // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
9052         if !go_onchain_before_fulfill && broadcast_alice {
9053                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9054                 assert_eq!(events.len(), 1);
9055                 match events[0] {
9056                         MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
9057                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9058                         },
9059                         _ => panic!("Unexpected event"),
9060                 };
9061         }
9062         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
9063         // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
9064         // Carol<->Bob's updated commitment transaction info.
9065         check_added_monitors!(nodes[1], 2);
9066
9067         let events = nodes[1].node.get_and_clear_pending_msg_events();
9068         assert_eq!(events.len(), 2);
9069         let bob_revocation = match events[0] {
9070                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
9071                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
9072                         (*msg).clone()
9073                 },
9074                 _ => panic!("Unexpected event"),
9075         };
9076         let bob_updates = match events[1] {
9077                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
9078                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
9079                         (*updates).clone()
9080                 },
9081                 _ => panic!("Unexpected event"),
9082         };
9083
9084         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
9085         check_added_monitors!(nodes[2], 1);
9086         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
9087         check_added_monitors!(nodes[2], 1);
9088
9089         let events = nodes[2].node.get_and_clear_pending_msg_events();
9090         assert_eq!(events.len(), 1);
9091         let carol_revocation = match events[0] {
9092                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
9093                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
9094                         (*msg).clone()
9095                 },
9096                 _ => panic!("Unexpected event"),
9097         };
9098         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
9099         check_added_monitors!(nodes[1], 1);
9100
9101         // If this test requires the force-closed channel to not be on-chain until after the fulfill,
9102         // here's where we put said channel's commitment tx on-chain.
9103         let mut txn_to_broadcast = alice_txn.clone();
9104         if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
9105         if !go_onchain_before_fulfill {
9106                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
9107                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
9108                 // If Bob was the one to force-close, he will have already passed these checks earlier.
9109                 if broadcast_alice {
9110                         check_closed_broadcast!(nodes[1], true);
9111                         check_added_monitors!(nodes[1], 1);
9112                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
9113                 }
9114                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9115                 if broadcast_alice {
9116                         // In `connect_block()`, the ChainMonitor and ChannelManager are separately notified about a
9117                         // new block being connected. The ChannelManager being notified triggers a monitor update,
9118                         // which triggers broadcasting our commitment tx and an HTLC-claiming tx. The ChainMonitor
9119                         // being notified triggers the HTLC-claiming tx redundantly, resulting in 3 total txs being
9120                         // broadcasted.
9121                         assert_eq!(bob_txn.len(), 3);
9122                         check_spends!(bob_txn[1], chan_ab.3);
9123                 } else {
9124                         assert_eq!(bob_txn.len(), 2);
9125                         check_spends!(bob_txn[0], chan_ab.3);
9126                 }
9127         }
9128
9129         // Step (6):
9130         // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
9131         // broadcasted commitment transaction.
9132         {
9133                 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
9134                 if go_onchain_before_fulfill {
9135                         // Bob should now have an extra broadcasted tx, for the preimage-claiming transaction.
9136                         assert_eq!(bob_txn.len(), 2);
9137                 }
9138                 let script_weight = match broadcast_alice {
9139                         true => OFFERED_HTLC_SCRIPT_WEIGHT,
9140                         false => ACCEPTED_HTLC_SCRIPT_WEIGHT
9141                 };
9142                 // If Alice force-closed and Bob didn't receive her commitment transaction until after he
9143                 // received Carol's fulfill, he broadcasts the HTLC-output-claiming transaction first. Else if
9144                 // Bob force closed or if he found out about Alice's commitment tx before receiving Carol's
9145                 // fulfill, then he broadcasts the HTLC-output-claiming transaction second.
9146                 if broadcast_alice && !go_onchain_before_fulfill {
9147                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
9148                         assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
9149                 } else {
9150                         check_spends!(bob_txn[1], txn_to_broadcast[0]);
9151                         assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
9152                 }
9153         }
9154 }
9155
9156 #[test]
9157 fn test_onchain_htlc_settlement_after_close() {
9158         do_test_onchain_htlc_settlement_after_close(true, true);
9159         do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
9160         do_test_onchain_htlc_settlement_after_close(true, false);
9161         do_test_onchain_htlc_settlement_after_close(false, false);
9162 }
9163
9164 #[test]
9165 fn test_duplicate_chan_id() {
9166         // Test that if a given peer tries to open a channel with the same channel_id as one that is
9167         // already open we reject it and keep the old channel.
9168         //
9169         // Previously, full_stack_target managed to figure out that if you tried to open two channels
9170         // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
9171         // the existing channel when we detect the duplicate new channel, screwing up our monitor
9172         // updating logic for the existing channel.
9173         let chanmon_cfgs = create_chanmon_cfgs(2);
9174         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9175         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9176         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9177
9178         // Create an initial channel
9179         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9180         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9181         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9182         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id()));
9183
9184         // Try to create a second channel with the same temporary_channel_id as the first and check
9185         // that it is rejected.
9186         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9187         {
9188                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9189                 assert_eq!(events.len(), 1);
9190                 match events[0] {
9191                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9192                                 // Technically, at this point, nodes[1] would be justified in thinking both the
9193                                 // first (valid) and second (invalid) channels are closed, given they both have
9194                                 // the same non-temporary channel_id. However, currently we do not, so we just
9195                                 // move forward with it.
9196                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9197                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9198                         },
9199                         _ => panic!("Unexpected event"),
9200                 }
9201         }
9202
9203         // Move the first channel through the funding flow...
9204         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
9205
9206         nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
9207         check_added_monitors!(nodes[0], 0);
9208
9209         let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9210         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
9211         {
9212                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
9213                 assert_eq!(added_monitors.len(), 1);
9214                 assert_eq!(added_monitors[0].0, funding_output);
9215                 added_monitors.clear();
9216         }
9217         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9218
9219         let funding_outpoint = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
9220         let channel_id = funding_outpoint.to_channel_id();
9221
9222         // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
9223         // temporary one).
9224
9225         // First try to open a second channel with a temporary channel id equal to the txid-based one.
9226         // Technically this is allowed by the spec, but we don't support it and there's little reason
9227         // to. Still, it shouldn't cause any other issues.
9228         open_chan_msg.temporary_channel_id = channel_id;
9229         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9230         {
9231                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9232                 assert_eq!(events.len(), 1);
9233                 match events[0] {
9234                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9235                                 // Technically, at this point, nodes[1] would be justified in thinking both
9236                                 // channels are closed, but currently we do not, so we just move forward with it.
9237                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9238                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9239                         },
9240                         _ => panic!("Unexpected event"),
9241                 }
9242         }
9243
9244         // Now try to create a second channel which has a duplicate funding output.
9245         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9246         let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9247         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_2_msg);
9248         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id()));
9249         create_funding_transaction(&nodes[0], 100000, 42); // Get and check the FundingGenerationReady event
9250
9251         let funding_created = {
9252                 let mut a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
9253                 let mut as_chan = a_channel_lock.by_id.get_mut(&open_chan_2_msg.temporary_channel_id).unwrap();
9254                 let logger = test_utils::TestLogger::new();
9255                 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
9256         };
9257         check_added_monitors!(nodes[0], 0);
9258         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
9259         // At this point we'll try to add a duplicate channel monitor, which will be rejected, but
9260         // still needs to be cleared here.
9261         check_added_monitors!(nodes[1], 1);
9262
9263         // ...still, nodes[1] will reject the duplicate channel.
9264         {
9265                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9266                 assert_eq!(events.len(), 1);
9267                 match events[0] {
9268                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9269                                 // Technically, at this point, nodes[1] would be justified in thinking both
9270                                 // channels are closed, but currently we do not, so we just move forward with it.
9271                                 assert_eq!(msg.channel_id, channel_id);
9272                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9273                         },
9274                         _ => panic!("Unexpected event"),
9275                 }
9276         }
9277
9278         // finally, finish creating the original channel and send a payment over it to make sure
9279         // everything is functional.
9280         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
9281         {
9282                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9283                 assert_eq!(added_monitors.len(), 1);
9284                 assert_eq!(added_monitors[0].0, funding_output);
9285                 added_monitors.clear();
9286         }
9287
9288         let events_4 = nodes[0].node.get_and_clear_pending_events();
9289         assert_eq!(events_4.len(), 0);
9290         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9291         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
9292
9293         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9294         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
9295         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9296         send_payment(&nodes[0], &[&nodes[1]], 8000000);
9297 }
9298
9299 #[test]
9300 fn test_error_chans_closed() {
9301         // Test that we properly handle error messages, closing appropriate channels.
9302         //
9303         // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
9304         // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
9305         // we can test various edge cases around it to ensure we don't regress.
9306         let chanmon_cfgs = create_chanmon_cfgs(3);
9307         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9308         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9309         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9310
9311         // Create some initial channels
9312         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9313         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9314         let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9315
9316         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9317         assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
9318         assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
9319
9320         // Closing a channel from a different peer has no effect
9321         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
9322         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9323
9324         // Closing one channel doesn't impact others
9325         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
9326         check_added_monitors!(nodes[0], 1);
9327         check_closed_broadcast!(nodes[0], false);
9328         check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
9329         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
9330         assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
9331         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);
9332         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);
9333
9334         // A null channel ID should close all channels
9335         let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9336         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
9337         check_added_monitors!(nodes[0], 2);
9338         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
9339         let events = nodes[0].node.get_and_clear_pending_msg_events();
9340         assert_eq!(events.len(), 2);
9341         match events[0] {
9342                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9343                         assert_eq!(msg.contents.flags & 2, 2);
9344                 },
9345                 _ => panic!("Unexpected event"),
9346         }
9347         match events[1] {
9348                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9349                         assert_eq!(msg.contents.flags & 2, 2);
9350                 },
9351                 _ => panic!("Unexpected event"),
9352         }
9353         // Note that at this point users of a standard PeerHandler will end up calling
9354         // peer_disconnected with no_connection_possible set to false, duplicating the
9355         // close-all-channels logic. That's OK, we don't want to end up not force-closing channels for
9356         // users with their own peer handling logic. We duplicate the call here, however.
9357         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9358         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9359
9360         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
9361         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9362         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9363 }
9364
9365 #[test]
9366 fn test_invalid_funding_tx() {
9367         // Test that we properly handle invalid funding transactions sent to us from a peer.
9368         //
9369         // Previously, all other major lightning implementations had failed to properly sanitize
9370         // funding transactions from their counterparties, leading to a multi-implementation critical
9371         // security vulnerability (though we always sanitized properly, we've previously had
9372         // un-released crashes in the sanitization process).
9373         let chanmon_cfgs = create_chanmon_cfgs(2);
9374         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9375         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9376         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9377
9378         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
9379         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id()));
9380         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id()));
9381
9382         let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], 100_000, 42);
9383         for output in tx.output.iter_mut() {
9384                 // Make the confirmed funding transaction have a bogus script_pubkey
9385                 output.script_pubkey = bitcoin::Script::new();
9386         }
9387
9388         nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, tx.clone(), 0).unwrap();
9389         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()));
9390         check_added_monitors!(nodes[1], 1);
9391
9392         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()));
9393         check_added_monitors!(nodes[0], 1);
9394
9395         let events_1 = nodes[0].node.get_and_clear_pending_events();
9396         assert_eq!(events_1.len(), 0);
9397
9398         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9399         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9400         nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9401
9402         let expected_err = "funding tx had wrong script/value or output index";
9403         confirm_transaction_at(&nodes[1], &tx, 1);
9404         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
9405         check_added_monitors!(nodes[1], 1);
9406         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9407         assert_eq!(events_2.len(), 1);
9408         if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9409                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9410                 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
9411                         assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
9412                 } else { panic!(); }
9413         } else { panic!(); }
9414         assert_eq!(nodes[1].node.list_channels().len(), 0);
9415 }
9416
9417 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9418         // In the first version of the chain::Confirm interface, after a refactor was made to not
9419         // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9420         // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9421         // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9422         // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9423         // spending transaction until height N+1 (or greater). This was due to the way
9424         // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9425         // spending transaction at the height the input transaction was confirmed at, not whether we
9426         // should broadcast a spending transaction at the current height.
9427         // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9428         // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9429         // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9430         // until we learned about an additional block.
9431         //
9432         // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9433         // aren't broadcasting transactions too early (ie not broadcasting them at all).
9434         let chanmon_cfgs = create_chanmon_cfgs(3);
9435         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9436         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9437         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9438         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9439
9440         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
9441         let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
9442         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9443         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
9444         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9445
9446         nodes[1].node.force_close_channel(&channel_id).unwrap();
9447         check_closed_broadcast!(nodes[1], true);
9448         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
9449         check_added_monitors!(nodes[1], 1);
9450         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9451         assert_eq!(node_txn.len(), 1);
9452
9453         let conf_height = nodes[1].best_block_info().1;
9454         if !test_height_before_timelock {
9455                 connect_blocks(&nodes[1], 24 * 6);
9456         }
9457         nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9458                 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9459         if test_height_before_timelock {
9460                 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9461                 // generate any events or broadcast any transactions
9462                 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9463                 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9464         } else {
9465                 // We should broadcast an HTLC transaction spending our funding transaction first
9466                 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9467                 assert_eq!(spending_txn.len(), 2);
9468                 assert_eq!(spending_txn[0], node_txn[0]);
9469                 check_spends!(spending_txn[1], node_txn[0]);
9470                 // We should also generate a SpendableOutputs event with the to_self output (as its
9471                 // timelock is up).
9472                 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9473                 assert_eq!(descriptor_spend_txn.len(), 1);
9474
9475                 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9476                 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9477                 // additional block built on top of the current chain.
9478                 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9479                         &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9480                 expect_pending_htlcs_forwardable!(nodes[1]);
9481                 check_added_monitors!(nodes[1], 1);
9482
9483                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9484                 assert!(updates.update_add_htlcs.is_empty());
9485                 assert!(updates.update_fulfill_htlcs.is_empty());
9486                 assert_eq!(updates.update_fail_htlcs.len(), 1);
9487                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9488                 assert!(updates.update_fee.is_none());
9489                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9490                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9491                 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9492         }
9493 }
9494
9495 #[test]
9496 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9497         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9498         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9499 }
9500
9501 #[test]
9502 fn test_forwardable_regen() {
9503         // Tests that if we reload a ChannelManager while forwards are pending we will regenerate the
9504         // PendingHTLCsForwardable event automatically, ensuring we don't forget to forward/receive
9505         // HTLCs.
9506         // We test it for both payment receipt and payment forwarding.
9507
9508         let chanmon_cfgs = create_chanmon_cfgs(3);
9509         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9510         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9511         let persister: test_utils::TestPersister;
9512         let new_chain_monitor: test_utils::TestChainMonitor;
9513         let nodes_1_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
9514         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9515         let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
9516         let chan_id_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known()).2;
9517
9518         // First send a payment to nodes[1]
9519         let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
9520         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
9521         check_added_monitors!(nodes[0], 1);
9522
9523         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9524         assert_eq!(events.len(), 1);
9525         let payment_event = SendEvent::from_event(events.pop().unwrap());
9526         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9527         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9528
9529         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9530
9531         // Next send a payment which is forwarded by nodes[1]
9532         let (route_2, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 200_000);
9533         nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
9534         check_added_monitors!(nodes[0], 1);
9535
9536         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9537         assert_eq!(events.len(), 1);
9538         let payment_event = SendEvent::from_event(events.pop().unwrap());
9539         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9540         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9541
9542         // There is already a PendingHTLCsForwardable event "pending" so another one will not be
9543         // generated
9544         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
9545
9546         // Now restart nodes[1] and make sure it regenerates a single PendingHTLCsForwardable
9547         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9548         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9549
9550         let nodes_1_serialized = nodes[1].node.encode();
9551         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9552         let mut chan_1_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9553         get_monitor!(nodes[1], chan_id_1).write(&mut chan_0_monitor_serialized).unwrap();
9554         get_monitor!(nodes[1], chan_id_2).write(&mut chan_1_monitor_serialized).unwrap();
9555
9556         persister = test_utils::TestPersister::new();
9557         let keys_manager = &chanmon_cfgs[1].keys_manager;
9558         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);
9559         nodes[1].chain_monitor = &new_chain_monitor;
9560
9561         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
9562         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9563                 &mut chan_0_monitor_read, keys_manager).unwrap();
9564         assert!(chan_0_monitor_read.is_empty());
9565         let mut chan_1_monitor_read = &chan_1_monitor_serialized.0[..];
9566         let (_, mut chan_1_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9567                 &mut chan_1_monitor_read, keys_manager).unwrap();
9568         assert!(chan_1_monitor_read.is_empty());
9569
9570         let mut nodes_1_read = &nodes_1_serialized[..];
9571         let (_, nodes_1_deserialized_tmp) = {
9572                 let mut channel_monitors = HashMap::new();
9573                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
9574                 channel_monitors.insert(chan_1_monitor.get_funding_txo().0, &mut chan_1_monitor);
9575                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_1_read, ChannelManagerReadArgs {
9576                         default_config: UserConfig::default(),
9577                         keys_manager,
9578                         fee_estimator: node_cfgs[1].fee_estimator,
9579                         chain_monitor: nodes[1].chain_monitor,
9580                         tx_broadcaster: nodes[1].tx_broadcaster.clone(),
9581                         logger: nodes[1].logger,
9582                         channel_monitors,
9583                 }).unwrap()
9584         };
9585         nodes_1_deserialized = nodes_1_deserialized_tmp;
9586         assert!(nodes_1_read.is_empty());
9587
9588         assert!(nodes[1].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
9589         assert!(nodes[1].chain_monitor.watch_channel(chan_1_monitor.get_funding_txo().0, chan_1_monitor).is_ok());
9590         nodes[1].node = &nodes_1_deserialized;
9591         check_added_monitors!(nodes[1], 2);
9592
9593         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9594         // Note that nodes[1] and nodes[2] resend their funding_locked here since they haven't updated
9595         // the commitment state.
9596         reconnect_nodes(&nodes[1], &nodes[2], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9597
9598         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
9599
9600         expect_pending_htlcs_forwardable!(nodes[1]);
9601         expect_payment_received!(nodes[1], payment_hash, payment_secret, 100_000);
9602         check_added_monitors!(nodes[1], 1);
9603
9604         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9605         assert_eq!(events.len(), 1);
9606         let payment_event = SendEvent::from_event(events.pop().unwrap());
9607         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9608         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false);
9609         expect_pending_htlcs_forwardable!(nodes[2]);
9610         expect_payment_received!(nodes[2], payment_hash_2, payment_secret_2, 200_000);
9611
9612         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
9613         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage_2);
9614 }
9615
9616 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
9617         let chanmon_cfgs = create_chanmon_cfgs(2);
9618         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9619         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9620         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9621
9622         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9623
9624         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
9625                 .with_features(InvoiceFeatures::known());
9626         let route = get_route!(nodes[0], payment_params, 10_000, TEST_FINAL_CLTV).unwrap();
9627
9628         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9629
9630         {
9631                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
9632                 check_added_monitors!(nodes[0], 1);
9633                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9634                 assert_eq!(events.len(), 1);
9635                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9636                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9637                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9638         }
9639         expect_pending_htlcs_forwardable!(nodes[1]);
9640         expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9641
9642         {
9643                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
9644                 check_added_monitors!(nodes[0], 1);
9645                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9646                 assert_eq!(events.len(), 1);
9647                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9648                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9649                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9650                 // At this point, nodes[1] would notice it has too much value for the payment. It will
9651                 // assume the second is a privacy attack (no longer particularly relevant
9652                 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9653                 // the first HTLC delivered above.
9654         }
9655
9656         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9657         nodes[1].node.process_pending_htlc_forwards();
9658
9659         if test_for_second_fail_panic {
9660                 // Now we go fail back the first HTLC from the user end.
9661                 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9662
9663                 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9664                 nodes[1].node.process_pending_htlc_forwards();
9665
9666                 check_added_monitors!(nodes[1], 1);
9667                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9668                 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9669
9670                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9671                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9672                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9673
9674                 let failure_events = nodes[0].node.get_and_clear_pending_events();
9675                 assert_eq!(failure_events.len(), 2);
9676                 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9677                 if let Event::PaymentPathFailed { .. } = failure_events[1] {} else { panic!(); }
9678         } else {
9679                 // Let the second HTLC fail and claim the first
9680                 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9681                 nodes[1].node.process_pending_htlc_forwards();
9682
9683                 check_added_monitors!(nodes[1], 1);
9684                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9685                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9686                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9687
9688                 expect_payment_failed_conditions!(nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9689
9690                 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9691         }
9692 }
9693
9694 #[test]
9695 fn test_dup_htlc_second_fail_panic() {
9696         // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9697         // value for the payment, we'd fail back both HTLCs after generating a `PaymentReceived` event.
9698         // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9699         // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9700         do_test_dup_htlc_second_rejected(true);
9701 }
9702
9703 #[test]
9704 fn test_dup_htlc_second_rejected() {
9705         // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9706         // simply reject the second HTLC but are still able to claim the first HTLC.
9707         do_test_dup_htlc_second_rejected(false);
9708 }
9709
9710 #[test]
9711 fn test_inconsistent_mpp_params() {
9712         // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9713         // such HTLC and allow the second to stay.
9714         let chanmon_cfgs = create_chanmon_cfgs(4);
9715         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9716         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9717         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9718
9719         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9720         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9721         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9722         create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9723
9724         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id())
9725                 .with_features(InvoiceFeatures::known());
9726         let mut route = get_route!(nodes[0], payment_params, 15_000_000, TEST_FINAL_CLTV).unwrap();
9727         assert_eq!(route.paths.len(), 2);
9728         route.paths.sort_by(|path_a, _| {
9729                 // Sort the path so that the path through nodes[1] comes first
9730                 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
9731                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9732         });
9733         let payment_params_opt = Some(payment_params);
9734
9735         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9736
9737         let cur_height = nodes[0].best_block_info().1;
9738         let payment_id = PaymentId([42; 32]);
9739         {
9740                 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).unwrap();
9741                 check_added_monitors!(nodes[0], 1);
9742
9743                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9744                 assert_eq!(events.len(), 1);
9745                 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9746         }
9747         assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9748
9749         {
9750                 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).unwrap();
9751                 check_added_monitors!(nodes[0], 1);
9752
9753                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9754                 assert_eq!(events.len(), 1);
9755                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9756
9757                 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9758                 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9759
9760                 expect_pending_htlcs_forwardable!(nodes[2]);
9761                 check_added_monitors!(nodes[2], 1);
9762
9763                 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9764                 assert_eq!(events.len(), 1);
9765                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9766
9767                 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9768                 check_added_monitors!(nodes[3], 0);
9769                 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9770
9771                 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9772                 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9773                 // post-payment_secrets) and fail back the new HTLC.
9774         }
9775         expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9776         nodes[3].node.process_pending_htlc_forwards();
9777         expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9778         nodes[3].node.process_pending_htlc_forwards();
9779
9780         check_added_monitors!(nodes[3], 1);
9781
9782         let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9783         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9784         commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9785
9786         expect_pending_htlcs_forwardable!(nodes[2]);
9787         check_added_monitors!(nodes[2], 1);
9788
9789         let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9790         nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9791         commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9792
9793         expect_payment_failed_conditions!(nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9794
9795         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).unwrap();
9796         check_added_monitors!(nodes[0], 1);
9797
9798         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9799         assert_eq!(events.len(), 1);
9800         pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9801
9802         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9803 }
9804
9805 #[test]
9806 fn test_keysend_payments_to_public_node() {
9807         let chanmon_cfgs = create_chanmon_cfgs(2);
9808         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9809         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9810         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9811
9812         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9813         let network_graph = nodes[0].network_graph;
9814         let payer_pubkey = nodes[0].node.get_our_node_id();
9815         let payee_pubkey = nodes[1].node.get_our_node_id();
9816         let route_params = RouteParameters {
9817                 payment_params: PaymentParameters::for_keysend(payee_pubkey),
9818                 final_value_msat: 10000,
9819                 final_cltv_expiry_delta: 40,
9820         };
9821         let scorer = test_utils::TestScorer::with_penalty(0);
9822         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9823         let route = find_route(&payer_pubkey, &route_params, network_graph, None, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
9824
9825         let test_preimage = PaymentPreimage([42; 32]);
9826         let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9827         check_added_monitors!(nodes[0], 1);
9828         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9829         assert_eq!(events.len(), 1);
9830         let event = events.pop().unwrap();
9831         let path = vec![&nodes[1]];
9832         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9833         claim_payment(&nodes[0], &path, test_preimage);
9834 }
9835
9836 #[test]
9837 fn test_keysend_payments_to_private_node() {
9838         let chanmon_cfgs = create_chanmon_cfgs(2);
9839         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9840         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9841         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9842
9843         let payer_pubkey = nodes[0].node.get_our_node_id();
9844         let payee_pubkey = nodes[1].node.get_our_node_id();
9845         nodes[0].node.peer_connected(&payee_pubkey, &msgs::Init { features: InitFeatures::known(), remote_network_address: None });
9846         nodes[1].node.peer_connected(&payer_pubkey, &msgs::Init { features: InitFeatures::known(), remote_network_address: None });
9847
9848         let _chan = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
9849         let route_params = RouteParameters {
9850                 payment_params: PaymentParameters::for_keysend(payee_pubkey),
9851                 final_value_msat: 10000,
9852                 final_cltv_expiry_delta: 40,
9853         };
9854         let network_graph = nodes[0].network_graph;
9855         let first_hops = nodes[0].node.list_usable_channels();
9856         let scorer = test_utils::TestScorer::with_penalty(0);
9857         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9858         let route = find_route(
9859                 &payer_pubkey, &route_params, network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
9860                 nodes[0].logger, &scorer, &random_seed_bytes
9861         ).unwrap();
9862
9863         let test_preimage = PaymentPreimage([42; 32]);
9864         let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9865         check_added_monitors!(nodes[0], 1);
9866         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9867         assert_eq!(events.len(), 1);
9868         let event = events.pop().unwrap();
9869         let path = vec![&nodes[1]];
9870         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9871         claim_payment(&nodes[0], &path, test_preimage);
9872 }
9873
9874 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
9875 #[derive(Clone, Copy, PartialEq)]
9876 enum ExposureEvent {
9877         /// Breach occurs at HTLC forwarding (see `send_htlc`)
9878         AtHTLCForward,
9879         /// Breach occurs at HTLC reception (see `update_add_htlc`)
9880         AtHTLCReception,
9881         /// Breach occurs at outbound update_fee (see `send_update_fee`)
9882         AtUpdateFeeOutbound,
9883 }
9884
9885 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool) {
9886         // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
9887         // policy.
9888         //
9889         // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
9890         // trimmed-to-dust HTLC outbound balance and this new payment as included on next
9891         // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
9892         // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
9893         // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
9894         // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
9895         // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
9896         // might be available again for HTLC processing once the dust bandwidth has cleared up.
9897
9898         let chanmon_cfgs = create_chanmon_cfgs(2);
9899         let mut config = test_default_channel_config();
9900         config.channel_options.max_dust_htlc_exposure_msat = 5_000_000; // default setting value
9901         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9902         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
9903         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9904
9905         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
9906         let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9907         open_channel.max_htlc_value_in_flight_msat = 50_000_000;
9908         open_channel.max_accepted_htlcs = 60;
9909         if on_holder_tx {
9910                 open_channel.dust_limit_satoshis = 546;
9911         }
9912         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
9913         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9914         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
9915
9916         let opt_anchors = false;
9917
9918         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], 1_000_000, 42);
9919
9920         if on_holder_tx {
9921                 if let Some(mut chan) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&temporary_channel_id) {
9922                         chan.holder_dust_limit_satoshis = 546;
9923                 }
9924         }
9925
9926         nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
9927         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()));
9928         check_added_monitors!(nodes[1], 1);
9929
9930         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()));
9931         check_added_monitors!(nodes[0], 1);
9932
9933         let (funding_locked, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9934         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
9935         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9936
9937         let dust_buffer_feerate = {
9938                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
9939                 let chan = chan_lock.by_id.get(&channel_id).unwrap();
9940                 chan.get_dust_buffer_feerate(None) as u64
9941         };
9942         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;
9943         let dust_outbound_htlc_on_holder_tx: u64 = config.channel_options.max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
9944
9945         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;
9946         let dust_inbound_htlc_on_holder_tx: u64 = config.channel_options.max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
9947
9948         let dust_htlc_on_counterparty_tx: u64 = 25;
9949         let dust_htlc_on_counterparty_tx_msat: u64 = config.channel_options.max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
9950
9951         if on_holder_tx {
9952                 if dust_outbound_balance {
9953                         // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9954                         // Outbound dust balance: 4372 sats
9955                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
9956                         for i in 0..dust_outbound_htlc_on_holder_tx {
9957                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
9958                                 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at dust HTLC {}", i); }
9959                         }
9960                 } else {
9961                         // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9962                         // Inbound dust balance: 4372 sats
9963                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
9964                         for _ in 0..dust_inbound_htlc_on_holder_tx {
9965                                 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
9966                         }
9967                 }
9968         } else {
9969                 if dust_outbound_balance {
9970                         // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9971                         // Outbound dust balance: 5000 sats
9972                         for i in 0..dust_htlc_on_counterparty_tx {
9973                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
9974                                 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at dust HTLC {}", i); }
9975                         }
9976                 } else {
9977                         // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9978                         // Inbound dust balance: 5000 sats
9979                         for _ in 0..dust_htlc_on_counterparty_tx {
9980                                 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
9981                         }
9982                 }
9983         }
9984
9985         let dust_overflow = dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx + 1);
9986         if exposure_breach_event == ExposureEvent::AtHTLCForward {
9987                 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 });
9988                 let mut config = UserConfig::default();
9989                 // With default dust exposure: 5000 sats
9990                 if on_holder_tx {
9991                         let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * (dust_outbound_htlc_on_holder_tx + 1);
9992                         let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * dust_inbound_htlc_on_holder_tx + dust_outbound_htlc_on_holder_tx_msat;
9993                         unwrap_send_err!(nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)), 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_options.max_dust_htlc_exposure_msat)));
9994                 } else {
9995                         unwrap_send_err!(nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)), 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_options.max_dust_htlc_exposure_msat)));
9996                 }
9997         } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
9998                 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 });
9999                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
10000                 check_added_monitors!(nodes[1], 1);
10001                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
10002                 assert_eq!(events.len(), 1);
10003                 let payment_event = SendEvent::from_event(events.remove(0));
10004                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
10005                 // With default dust exposure: 5000 sats
10006                 if on_holder_tx {
10007                         // Outbound dust balance: 6399 sats
10008                         let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
10009                         let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
10010                         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_options.max_dust_htlc_exposure_msat), 1);
10011                 } else {
10012                         // Outbound dust balance: 5200 sats
10013                         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_options.max_dust_htlc_exposure_msat), 1);
10014                 }
10015         } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
10016                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 2_500_000);
10017                 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at update_fee-swallowed HTLC", ); }
10018                 {
10019                         let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
10020                         *feerate_lock = *feerate_lock * 10;
10021                 }
10022                 nodes[0].node.timer_tick_occurred();
10023                 check_added_monitors!(nodes[0], 1);
10024                 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);
10025         }
10026
10027         let _ = nodes[0].node.get_and_clear_pending_msg_events();
10028         let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
10029         added_monitors.clear();
10030 }
10031
10032 #[test]
10033 fn test_max_dust_htlc_exposure() {
10034         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true);
10035         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true);
10036         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true);
10037         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false);
10038         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false);
10039         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false);
10040         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true);
10041         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false);
10042         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true);
10043         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false);
10044         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false);
10045         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true);
10046 }