Merge pull request #1481 from TheBlueMatt/2022-05-new-chain-tests
[rust-lightning] / lightning / src / ln / functional_tests.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
8 // licenses.
9
10 //! Tests that test standing up a network of ChannelManagers, creating channels, sending
11 //! payments/messages between them, and often checking the resulting ChannelMonitors are able to
12 //! claim outputs on-chain.
13
14 use 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], &nodes[1].node.get_our_node_id(), 100000, 42);
519
520         if steps & 0x0f == 3 { return; }
521         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_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, &nodes[0].node.get_our_node_id()).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, &nodes[2].node.get_our_node_id()).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, &nodes[3].node.get_our_node_id()).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, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
2727                         assert_eq!(fee_earned_msat, Some(1000));
2728                         assert_eq!(prev_channel_id, chan_id);
2729                         assert_eq!(claim_from_onchain_tx, true);
2730                         assert_eq!(next_channel_id, Some(chan_2.2));
2731                 },
2732                 _ => panic!()
2733         }
2734         match forwarded_events[2] {
2735                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
2736                         assert_eq!(fee_earned_msat, Some(1000));
2737                         assert_eq!(prev_channel_id, chan_id);
2738                         assert_eq!(claim_from_onchain_tx, true);
2739                         assert_eq!(next_channel_id, Some(chan_2.2));
2740                 },
2741                 _ => panic!()
2742         }
2743         let events = nodes[1].node.get_and_clear_pending_msg_events();
2744         {
2745                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2746                 assert_eq!(added_monitors.len(), 2);
2747                 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2748                 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2749                 added_monitors.clear();
2750         }
2751         assert_eq!(events.len(), 3);
2752         match events[0] {
2753                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2754                 _ => panic!("Unexpected event"),
2755         }
2756         match events[1] {
2757                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2758                 _ => panic!("Unexpected event"),
2759         }
2760
2761         match events[2] {
2762                 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, .. } } => {
2763                         assert!(update_add_htlcs.is_empty());
2764                         assert!(update_fail_htlcs.is_empty());
2765                         assert_eq!(update_fulfill_htlcs.len(), 1);
2766                         assert!(update_fail_malformed_htlcs.is_empty());
2767                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2768                 },
2769                 _ => panic!("Unexpected event"),
2770         };
2771         macro_rules! check_tx_local_broadcast {
2772                 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2773                         let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2774                         assert_eq!(node_txn.len(), 3);
2775                         // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2776                         // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2777                         check_spends!(node_txn[1], $commitment_tx);
2778                         check_spends!(node_txn[2], $commitment_tx);
2779                         assert_ne!(node_txn[1].lock_time, 0);
2780                         assert_ne!(node_txn[2].lock_time, 0);
2781                         if $htlc_offered {
2782                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2783                                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2784                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2785                                 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2786                         } else {
2787                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2788                                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2789                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2790                                 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2791                         }
2792                         check_spends!(node_txn[0], $chan_tx);
2793                         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2794                         node_txn.clear();
2795                 } }
2796         }
2797         // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2798         // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2799         // timeout-claim of the output that nodes[2] just claimed via success.
2800         check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2801
2802         // Broadcast legit commitment tx from A on B's chain
2803         // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
2804         let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2805         check_spends!(node_a_commitment_tx[0], chan_1.3);
2806         mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2807         check_closed_broadcast!(nodes[1], true);
2808         check_added_monitors!(nodes[1], 1);
2809         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2810         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2811         assert_eq!(node_txn.len(), 6); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 3 (HTLC-Success, 2* RBF bumps of above HTLC txn)
2812         let commitment_spend =
2813                 if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2814                         check_spends!(node_txn[1], commitment_tx[0]);
2815                         check_spends!(node_txn[2], commitment_tx[0]);
2816                         assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2817                         &node_txn[0]
2818                 } else {
2819                         check_spends!(node_txn[0], commitment_tx[0]);
2820                         check_spends!(node_txn[1], commitment_tx[0]);
2821                         assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2822                         &node_txn[2]
2823                 };
2824
2825         check_spends!(commitment_spend, node_a_commitment_tx[0]);
2826         assert_eq!(commitment_spend.input.len(), 2);
2827         assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2828         assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2829         assert_eq!(commitment_spend.lock_time, 0);
2830         assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2831         check_spends!(node_txn[3], chan_1.3);
2832         assert_eq!(node_txn[3].input[0].witness.clone().last().unwrap().len(), 71);
2833         check_spends!(node_txn[4], node_txn[3]);
2834         check_spends!(node_txn[5], node_txn[3]);
2835         // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2836         // we already checked the same situation with A.
2837
2838         // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2839         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2840         connect_block(&nodes[0], &Block { header, txdata: vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()] });
2841         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2842         check_closed_broadcast!(nodes[0], true);
2843         check_added_monitors!(nodes[0], 1);
2844         let events = nodes[0].node.get_and_clear_pending_events();
2845         assert_eq!(events.len(), 5);
2846         let mut first_claimed = false;
2847         for event in events {
2848                 match event {
2849                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
2850                                 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
2851                                         assert!(!first_claimed);
2852                                         first_claimed = true;
2853                                 } else {
2854                                         assert_eq!(payment_preimage, our_payment_preimage_2);
2855                                         assert_eq!(payment_hash, payment_hash_2);
2856                                 }
2857                         },
2858                         Event::PaymentPathSuccessful { .. } => {},
2859                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
2860                         _ => panic!("Unexpected event"),
2861                 }
2862         }
2863         check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0], chan_1.3);
2864 }
2865
2866 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2867         // Test that in case of a unilateral close onchain, we detect the state of output and
2868         // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2869         // broadcasting the right event to other nodes in payment path.
2870         // A ------------------> B ----------------------> C (timeout)
2871         //    B's commitment tx                 C's commitment tx
2872         //            \                                  \
2873         //         B's HTLC timeout tx               B's timeout tx
2874
2875         let chanmon_cfgs = create_chanmon_cfgs(3);
2876         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2877         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2878         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2879         *nodes[0].connect_style.borrow_mut() = connect_style;
2880         *nodes[1].connect_style.borrow_mut() = connect_style;
2881         *nodes[2].connect_style.borrow_mut() = connect_style;
2882
2883         // Create some intial channels
2884         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2885         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2886
2887         // Rebalance the network a bit by relaying one payment thorugh all the channels...
2888         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2889         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2890
2891         let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2892
2893         // Broadcast legit commitment tx from C on B's chain
2894         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2895         check_spends!(commitment_tx[0], chan_2.3);
2896         nodes[2].node.fail_htlc_backwards(&payment_hash);
2897         check_added_monitors!(nodes[2], 0);
2898         expect_pending_htlcs_forwardable!(nodes[2]);
2899         check_added_monitors!(nodes[2], 1);
2900
2901         let events = nodes[2].node.get_and_clear_pending_msg_events();
2902         assert_eq!(events.len(), 1);
2903         match events[0] {
2904                 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, .. } } => {
2905                         assert!(update_add_htlcs.is_empty());
2906                         assert!(!update_fail_htlcs.is_empty());
2907                         assert!(update_fulfill_htlcs.is_empty());
2908                         assert!(update_fail_malformed_htlcs.is_empty());
2909                         assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2910                 },
2911                 _ => panic!("Unexpected event"),
2912         };
2913         mine_transaction(&nodes[2], &commitment_tx[0]);
2914         check_closed_broadcast!(nodes[2], true);
2915         check_added_monitors!(nodes[2], 1);
2916         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2917         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2918         assert_eq!(node_txn.len(), 1);
2919         check_spends!(node_txn[0], chan_2.3);
2920         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2921
2922         // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2923         // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2924         connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2925         mine_transaction(&nodes[1], &commitment_tx[0]);
2926         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2927         let timeout_tx;
2928         {
2929                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2930                 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
2931                 assert_eq!(node_txn[0], node_txn[3]);
2932                 assert_eq!(node_txn[1], node_txn[4]);
2933
2934                 check_spends!(node_txn[2], commitment_tx[0]);
2935                 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2936
2937                 check_spends!(node_txn[0], chan_2.3);
2938                 check_spends!(node_txn[1], node_txn[0]);
2939                 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2940                 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2941
2942                 timeout_tx = node_txn[2].clone();
2943                 node_txn.clear();
2944         }
2945
2946         mine_transaction(&nodes[1], &timeout_tx);
2947         check_added_monitors!(nodes[1], 1);
2948         check_closed_broadcast!(nodes[1], true);
2949         {
2950                 // B will rebroadcast a fee-bumped timeout transaction here.
2951                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2952                 assert_eq!(node_txn.len(), 1);
2953                 check_spends!(node_txn[0], commitment_tx[0]);
2954         }
2955
2956         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2957         {
2958                 // B may rebroadcast its own holder commitment transaction here, as a safeguard against
2959                 // some incredibly unlikely partial-eclipse-attack scenarios. That said, because the
2960                 // original commitment_tx[0] (also spending chan_2.3) has reached ANTI_REORG_DELAY B really
2961                 // shouldn't broadcast anything here, and in some connect style scenarios we do not.
2962                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2963                 if node_txn.len() == 1 {
2964                         check_spends!(node_txn[0], chan_2.3);
2965                 } else {
2966                         assert_eq!(node_txn.len(), 0);
2967                 }
2968         }
2969
2970         expect_pending_htlcs_forwardable!(nodes[1]);
2971         check_added_monitors!(nodes[1], 1);
2972         let events = nodes[1].node.get_and_clear_pending_msg_events();
2973         assert_eq!(events.len(), 1);
2974         match events[0] {
2975                 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, .. } } => {
2976                         assert!(update_add_htlcs.is_empty());
2977                         assert!(!update_fail_htlcs.is_empty());
2978                         assert!(update_fulfill_htlcs.is_empty());
2979                         assert!(update_fail_malformed_htlcs.is_empty());
2980                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2981                 },
2982                 _ => panic!("Unexpected event"),
2983         };
2984
2985         // Broadcast legit commitment tx from B on A's chain
2986         let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
2987         check_spends!(commitment_tx[0], chan_1.3);
2988
2989         mine_transaction(&nodes[0], &commitment_tx[0]);
2990         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2991
2992         check_closed_broadcast!(nodes[0], true);
2993         check_added_monitors!(nodes[0], 1);
2994         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2995         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 commitment tx, ChannelMonitor : 1 timeout tx
2996         assert_eq!(node_txn.len(), 2);
2997         check_spends!(node_txn[0], chan_1.3);
2998         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2999         check_spends!(node_txn[1], commitment_tx[0]);
3000         assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3001 }
3002
3003 #[test]
3004 fn test_htlc_on_chain_timeout() {
3005         do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
3006         do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
3007         do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
3008 }
3009
3010 #[test]
3011 fn test_simple_commitment_revoked_fail_backward() {
3012         // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3013         // and fail backward accordingly.
3014
3015         let chanmon_cfgs = create_chanmon_cfgs(3);
3016         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3017         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3018         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3019
3020         // Create some initial channels
3021         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3022         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3023
3024         let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3025         // Get the will-be-revoked local txn from nodes[2]
3026         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3027         // Revoke the old state
3028         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3029
3030         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3031
3032         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3033         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3034         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3035         check_added_monitors!(nodes[1], 1);
3036         check_closed_broadcast!(nodes[1], true);
3037
3038         expect_pending_htlcs_forwardable!(nodes[1]);
3039         check_added_monitors!(nodes[1], 1);
3040         let events = nodes[1].node.get_and_clear_pending_msg_events();
3041         assert_eq!(events.len(), 1);
3042         match events[0] {
3043                 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, .. } } => {
3044                         assert!(update_add_htlcs.is_empty());
3045                         assert_eq!(update_fail_htlcs.len(), 1);
3046                         assert!(update_fulfill_htlcs.is_empty());
3047                         assert!(update_fail_malformed_htlcs.is_empty());
3048                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3049
3050                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3051                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3052                         expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3053                 },
3054                 _ => panic!("Unexpected event"),
3055         }
3056 }
3057
3058 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3059         // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3060         // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3061         // commitment transaction anymore.
3062         // To do this, we have the peer which will broadcast a revoked commitment transaction send
3063         // a number of update_fail/commitment_signed updates without ever sending the RAA in
3064         // response to our commitment_signed. This is somewhat misbehavior-y, though not
3065         // technically disallowed and we should probably handle it reasonably.
3066         // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3067         // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3068         // transactions:
3069         // * Once we move it out of our holding cell/add it, we will immediately include it in a
3070         //   commitment_signed (implying it will be in the latest remote commitment transaction).
3071         // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3072         //   and once they revoke the previous commitment transaction (allowing us to send a new
3073         //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3074         let chanmon_cfgs = create_chanmon_cfgs(3);
3075         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3076         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3077         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3078
3079         // Create some initial channels
3080         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3081         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3082
3083         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 });
3084         // Get the will-be-revoked local txn from nodes[2]
3085         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3086         assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3087         // Revoke the old state
3088         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3089
3090         let value = if use_dust {
3091                 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3092                 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3093                 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3094         } else { 3000000 };
3095
3096         let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3097         let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3098         let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3099
3100         assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash));
3101         expect_pending_htlcs_forwardable!(nodes[2]);
3102         check_added_monitors!(nodes[2], 1);
3103         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3104         assert!(updates.update_add_htlcs.is_empty());
3105         assert!(updates.update_fulfill_htlcs.is_empty());
3106         assert!(updates.update_fail_malformed_htlcs.is_empty());
3107         assert_eq!(updates.update_fail_htlcs.len(), 1);
3108         assert!(updates.update_fee.is_none());
3109         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3110         let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3111         // Drop the last RAA from 3 -> 2
3112
3113         assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash));
3114         expect_pending_htlcs_forwardable!(nodes[2]);
3115         check_added_monitors!(nodes[2], 1);
3116         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3117         assert!(updates.update_add_htlcs.is_empty());
3118         assert!(updates.update_fulfill_htlcs.is_empty());
3119         assert!(updates.update_fail_malformed_htlcs.is_empty());
3120         assert_eq!(updates.update_fail_htlcs.len(), 1);
3121         assert!(updates.update_fee.is_none());
3122         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3123         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3124         check_added_monitors!(nodes[1], 1);
3125         // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3126         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3127         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3128         check_added_monitors!(nodes[2], 1);
3129
3130         assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash));
3131         expect_pending_htlcs_forwardable!(nodes[2]);
3132         check_added_monitors!(nodes[2], 1);
3133         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3134         assert!(updates.update_add_htlcs.is_empty());
3135         assert!(updates.update_fulfill_htlcs.is_empty());
3136         assert!(updates.update_fail_malformed_htlcs.is_empty());
3137         assert_eq!(updates.update_fail_htlcs.len(), 1);
3138         assert!(updates.update_fee.is_none());
3139         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3140         // At this point first_payment_hash has dropped out of the latest two commitment
3141         // transactions that nodes[1] is tracking...
3142         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3143         check_added_monitors!(nodes[1], 1);
3144         // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3145         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3146         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3147         check_added_monitors!(nodes[2], 1);
3148
3149         // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3150         // on nodes[2]'s RAA.
3151         let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3152         nodes[1].node.send_payment(&route, fourth_payment_hash, &Some(fourth_payment_secret)).unwrap();
3153         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3154         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3155         check_added_monitors!(nodes[1], 0);
3156
3157         if deliver_bs_raa {
3158                 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3159                 // One monitor for the new revocation preimage, no second on as we won't generate a new
3160                 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3161                 check_added_monitors!(nodes[1], 1);
3162                 let events = nodes[1].node.get_and_clear_pending_events();
3163                 assert_eq!(events.len(), 1);
3164                 match events[0] {
3165                         Event::PendingHTLCsForwardable { .. } => { },
3166                         _ => panic!("Unexpected event"),
3167                 };
3168                 // Deliberately don't process the pending fail-back so they all fail back at once after
3169                 // block connection just like the !deliver_bs_raa case
3170         }
3171
3172         let mut failed_htlcs = HashSet::new();
3173         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3174
3175         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3176         check_added_monitors!(nodes[1], 1);
3177         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3178         assert!(ANTI_REORG_DELAY > PAYMENT_EXPIRY_BLOCKS); // We assume payments will also expire
3179
3180         let events = nodes[1].node.get_and_clear_pending_events();
3181         assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 4 });
3182         match events[0] {
3183                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3184                 _ => panic!("Unexepected event"),
3185         }
3186         match events[1] {
3187                 Event::PaymentPathFailed { ref payment_hash, .. } => {
3188                         assert_eq!(*payment_hash, fourth_payment_hash);
3189                 },
3190                 _ => panic!("Unexpected event"),
3191         }
3192         if !deliver_bs_raa {
3193                 match events[2] {
3194                         Event::PaymentFailed { ref payment_hash, .. } => {
3195                                 assert_eq!(*payment_hash, fourth_payment_hash);
3196                         },
3197                         _ => panic!("Unexpected event"),
3198                 }
3199                 match events[3] {
3200                         Event::PendingHTLCsForwardable { .. } => { },
3201                         _ => panic!("Unexpected event"),
3202                 };
3203         }
3204         nodes[1].node.process_pending_htlc_forwards();
3205         check_added_monitors!(nodes[1], 1);
3206
3207         let events = nodes[1].node.get_and_clear_pending_msg_events();
3208         assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3209         match events[if deliver_bs_raa { 1 } else { 0 }] {
3210                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3211                 _ => panic!("Unexpected event"),
3212         }
3213         match events[if deliver_bs_raa { 2 } else { 1 }] {
3214                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3215                         assert_eq!(channel_id, chan_2.2);
3216                         assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3217                 },
3218                 _ => panic!("Unexpected event"),
3219         }
3220         if deliver_bs_raa {
3221                 match events[0] {
3222                         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, .. } } => {
3223                                 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3224                                 assert_eq!(update_add_htlcs.len(), 1);
3225                                 assert!(update_fulfill_htlcs.is_empty());
3226                                 assert!(update_fail_htlcs.is_empty());
3227                                 assert!(update_fail_malformed_htlcs.is_empty());
3228                         },
3229                         _ => panic!("Unexpected event"),
3230                 }
3231         }
3232         match events[if deliver_bs_raa { 3 } else { 2 }] {
3233                 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, ref commitment_signed, .. } } => {
3234                         assert!(update_add_htlcs.is_empty());
3235                         assert_eq!(update_fail_htlcs.len(), 3);
3236                         assert!(update_fulfill_htlcs.is_empty());
3237                         assert!(update_fail_malformed_htlcs.is_empty());
3238                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3239
3240                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3241                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3242                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3243
3244                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3245
3246                         let events = nodes[0].node.get_and_clear_pending_events();
3247                         assert_eq!(events.len(), 3);
3248                         match events[0] {
3249                                 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3250                                         assert!(failed_htlcs.insert(payment_hash.0));
3251                                         // If we delivered B's RAA we got an unknown preimage error, not something
3252                                         // that we should update our routing table for.
3253                                         if !deliver_bs_raa {
3254                                                 assert!(network_update.is_some());
3255                                         }
3256                                 },
3257                                 _ => panic!("Unexpected event"),
3258                         }
3259                         match events[1] {
3260                                 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3261                                         assert!(failed_htlcs.insert(payment_hash.0));
3262                                         assert!(network_update.is_some());
3263                                 },
3264                                 _ => panic!("Unexpected event"),
3265                         }
3266                         match events[2] {
3267                                 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3268                                         assert!(failed_htlcs.insert(payment_hash.0));
3269                                         assert!(network_update.is_some());
3270                                 },
3271                                 _ => panic!("Unexpected event"),
3272                         }
3273                 },
3274                 _ => panic!("Unexpected event"),
3275         }
3276
3277         assert!(failed_htlcs.contains(&first_payment_hash.0));
3278         assert!(failed_htlcs.contains(&second_payment_hash.0));
3279         assert!(failed_htlcs.contains(&third_payment_hash.0));
3280 }
3281
3282 #[test]
3283 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3284         do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3285         do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3286         do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3287         do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3288 }
3289
3290 #[test]
3291 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3292         do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3293         do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3294         do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3295         do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3296 }
3297
3298 #[test]
3299 fn fail_backward_pending_htlc_upon_channel_failure() {
3300         let chanmon_cfgs = create_chanmon_cfgs(2);
3301         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3302         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3303         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3304         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
3305
3306         // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3307         {
3308                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3309                 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
3310                 check_added_monitors!(nodes[0], 1);
3311
3312                 let payment_event = {
3313                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3314                         assert_eq!(events.len(), 1);
3315                         SendEvent::from_event(events.remove(0))
3316                 };
3317                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3318                 assert_eq!(payment_event.msgs.len(), 1);
3319         }
3320
3321         // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3322         let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3323         {
3324                 nodes[0].node.send_payment(&route, failed_payment_hash, &Some(failed_payment_secret)).unwrap();
3325                 check_added_monitors!(nodes[0], 0);
3326
3327                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3328         }
3329
3330         // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3331         {
3332                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3333
3334                 let secp_ctx = Secp256k1::new();
3335                 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3336                 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3337                 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &Some(payment_secret), current_height, &None).unwrap();
3338                 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3339                 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3340
3341                 // Send a 0-msat update_add_htlc to fail the channel.
3342                 let update_add_htlc = msgs::UpdateAddHTLC {
3343                         channel_id: chan.2,
3344                         htlc_id: 0,
3345                         amount_msat: 0,
3346                         payment_hash,
3347                         cltv_expiry,
3348                         onion_routing_packet,
3349                 };
3350                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3351         }
3352         let events = nodes[0].node.get_and_clear_pending_events();
3353         assert_eq!(events.len(), 2);
3354         // Check that Alice fails backward the pending HTLC from the second payment.
3355         match events[0] {
3356                 Event::PaymentPathFailed { payment_hash, .. } => {
3357                         assert_eq!(payment_hash, failed_payment_hash);
3358                 },
3359                 _ => panic!("Unexpected event"),
3360         }
3361         match events[1] {
3362                 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3363                         assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3364                 },
3365                 _ => panic!("Unexpected event {:?}", events[1]),
3366         }
3367         check_closed_broadcast!(nodes[0], true);
3368         check_added_monitors!(nodes[0], 1);
3369 }
3370
3371 #[test]
3372 fn test_htlc_ignore_latest_remote_commitment() {
3373         // Test that HTLC transactions spending the latest remote commitment transaction are simply
3374         // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3375         let chanmon_cfgs = create_chanmon_cfgs(2);
3376         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3377         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3378         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3379         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3380
3381         route_payment(&nodes[0], &[&nodes[1]], 10000000);
3382         nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3383         connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3384         check_closed_broadcast!(nodes[0], true);
3385         check_added_monitors!(nodes[0], 1);
3386         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
3387
3388         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3389         assert_eq!(node_txn.len(), 3);
3390         assert_eq!(node_txn[0], node_txn[1]);
3391
3392         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3393         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3394         check_closed_broadcast!(nodes[1], true);
3395         check_added_monitors!(nodes[1], 1);
3396         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3397
3398         // Duplicate the connect_block call since this may happen due to other listeners
3399         // registering new transactions
3400         header.prev_blockhash = header.block_hash();
3401         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[2].clone()]});
3402 }
3403
3404 #[test]
3405 fn test_force_close_fail_back() {
3406         // Check which HTLCs are failed-backwards on channel force-closure
3407         let chanmon_cfgs = create_chanmon_cfgs(3);
3408         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3409         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3410         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3411         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3412         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3413
3414         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3415
3416         let mut payment_event = {
3417                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
3418                 check_added_monitors!(nodes[0], 1);
3419
3420                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3421                 assert_eq!(events.len(), 1);
3422                 SendEvent::from_event(events.remove(0))
3423         };
3424
3425         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3426         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3427
3428         expect_pending_htlcs_forwardable!(nodes[1]);
3429
3430         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3431         assert_eq!(events_2.len(), 1);
3432         payment_event = SendEvent::from_event(events_2.remove(0));
3433         assert_eq!(payment_event.msgs.len(), 1);
3434
3435         check_added_monitors!(nodes[1], 1);
3436         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3437         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3438         check_added_monitors!(nodes[2], 1);
3439         let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3440
3441         // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3442         // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3443         // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3444
3445         nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3446         check_closed_broadcast!(nodes[2], true);
3447         check_added_monitors!(nodes[2], 1);
3448         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
3449         let tx = {
3450                 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3451                 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3452                 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3453                 // back to nodes[1] upon timeout otherwise.
3454                 assert_eq!(node_txn.len(), 1);
3455                 node_txn.remove(0)
3456         };
3457
3458         mine_transaction(&nodes[1], &tx);
3459
3460         // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3461         check_closed_broadcast!(nodes[1], true);
3462         check_added_monitors!(nodes[1], 1);
3463         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3464
3465         // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3466         {
3467                 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3468                         .provide_payment_preimage(&our_payment_hash, &our_payment_preimage, &node_cfgs[2].tx_broadcaster, &node_cfgs[2].fee_estimator, &node_cfgs[2].logger);
3469         }
3470         mine_transaction(&nodes[2], &tx);
3471         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3472         assert_eq!(node_txn.len(), 1);
3473         assert_eq!(node_txn[0].input.len(), 1);
3474         assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3475         assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3476         assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3477
3478         check_spends!(node_txn[0], tx);
3479 }
3480
3481 #[test]
3482 fn test_dup_events_on_peer_disconnect() {
3483         // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3484         // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3485         // as we used to generate the event immediately upon receipt of the payment preimage in the
3486         // update_fulfill_htlc message.
3487
3488         let chanmon_cfgs = create_chanmon_cfgs(2);
3489         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3490         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3491         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3492         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3493
3494         let payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 1000000).0;
3495
3496         assert!(nodes[1].node.claim_funds(payment_preimage));
3497         check_added_monitors!(nodes[1], 1);
3498         let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3499         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3500         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
3501
3502         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3503         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3504
3505         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3506         expect_payment_path_successful!(nodes[0]);
3507 }
3508
3509 #[test]
3510 fn test_peer_disconnected_before_funding_broadcasted() {
3511         // Test that channels are closed with `ClosureReason::DisconnectedPeer` if the peer disconnects
3512         // before the funding transaction has been broadcasted.
3513         let chanmon_cfgs = create_chanmon_cfgs(2);
3514         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3515         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3516         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3517
3518         // Open a channel between `nodes[0]` and `nodes[1]`, for which the funding transaction is never
3519         // broadcasted, even though it's created by `nodes[0]`.
3520         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();
3521         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
3522         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
3523         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
3524         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
3525
3526         let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
3527         assert_eq!(temporary_channel_id, expected_temporary_channel_id);
3528
3529         assert!(nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
3530
3531         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
3532         assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
3533
3534         // Even though the funding transaction is created by `nodes[0]`, the `FundingCreated` msg is
3535         // never sent to `nodes[1]`, and therefore the tx is never signed by either party nor
3536         // broadcasted.
3537         {
3538                 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
3539         }
3540
3541         // Ensure that the channel is closed with `ClosureReason::DisconnectedPeer` when the peers are
3542         // disconnected before the funding transaction was broadcasted.
3543         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3544         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3545
3546         check_closed_event!(nodes[0], 1, ClosureReason::DisconnectedPeer);
3547         check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
3548 }
3549
3550 #[test]
3551 fn test_simple_peer_disconnect() {
3552         // Test that we can reconnect when there are no lost messages
3553         let chanmon_cfgs = create_chanmon_cfgs(3);
3554         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3555         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3556         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3557         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3558         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3559
3560         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3561         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3562         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3563
3564         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3565         let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3566         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3567         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3568
3569         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3570         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3571         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3572
3573         let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3574         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3575         let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3576         let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3577
3578         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3579         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3580
3581         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3582         fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3583
3584         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3585         {
3586                 let events = nodes[0].node.get_and_clear_pending_events();
3587                 assert_eq!(events.len(), 3);
3588                 match events[0] {
3589                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3590                                 assert_eq!(payment_preimage, payment_preimage_3);
3591                                 assert_eq!(payment_hash, payment_hash_3);
3592                         },
3593                         _ => panic!("Unexpected event"),
3594                 }
3595                 match events[1] {
3596                         Event::PaymentPathFailed { payment_hash, rejected_by_dest, .. } => {
3597                                 assert_eq!(payment_hash, payment_hash_5);
3598                                 assert!(rejected_by_dest);
3599                         },
3600                         _ => panic!("Unexpected event"),
3601                 }
3602                 match events[2] {
3603                         Event::PaymentPathSuccessful { .. } => {},
3604                         _ => panic!("Unexpected event"),
3605                 }
3606         }
3607
3608         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3609         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3610 }
3611
3612 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3613         // Test that we can reconnect when in-flight HTLC updates get dropped
3614         let chanmon_cfgs = create_chanmon_cfgs(2);
3615         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3616         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3617         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3618
3619         let mut as_funding_locked = None;
3620         if messages_delivered == 0 {
3621                 let (funding_locked, _, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3622                 as_funding_locked = Some(funding_locked);
3623                 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
3624                 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3625                 // it before the channel_reestablish message.
3626         } else {
3627                 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3628         }
3629
3630         let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3631
3632         let payment_event = {
3633                 nodes[0].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)).unwrap();
3634                 check_added_monitors!(nodes[0], 1);
3635
3636                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3637                 assert_eq!(events.len(), 1);
3638                 SendEvent::from_event(events.remove(0))
3639         };
3640         assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3641
3642         if messages_delivered < 2 {
3643                 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3644         } else {
3645                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3646                 if messages_delivered >= 3 {
3647                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3648                         check_added_monitors!(nodes[1], 1);
3649                         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3650
3651                         if messages_delivered >= 4 {
3652                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3653                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3654                                 check_added_monitors!(nodes[0], 1);
3655
3656                                 if messages_delivered >= 5 {
3657                                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3658                                         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3659                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3660                                         check_added_monitors!(nodes[0], 1);
3661
3662                                         if messages_delivered >= 6 {
3663                                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3664                                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3665                                                 check_added_monitors!(nodes[1], 1);
3666                                         }
3667                                 }
3668                         }
3669                 }
3670         }
3671
3672         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3673         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3674         if messages_delivered < 3 {
3675                 if simulate_broken_lnd {
3676                         // lnd has a long-standing bug where they send a funding_locked prior to a
3677                         // channel_reestablish if you reconnect prior to funding_locked time.
3678                         //
3679                         // Here we simulate that behavior, delivering a funding_locked immediately on
3680                         // reconnect. Note that we don't bother skipping the now-duplicate funding_locked sent
3681                         // in `reconnect_nodes` but we currently don't fail based on that.
3682                         //
3683                         // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3684                         nodes[1].node.handle_funding_locked(&nodes[0].node.get_our_node_id(), &as_funding_locked.as_ref().unwrap().0);
3685                 }
3686                 // Even if the funding_locked messages get exchanged, as long as nothing further was
3687                 // received on either side, both sides will need to resend them.
3688                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3689         } else if messages_delivered == 3 {
3690                 // nodes[0] still wants its RAA + commitment_signed
3691                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3692         } else if messages_delivered == 4 {
3693                 // nodes[0] still wants its commitment_signed
3694                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3695         } else if messages_delivered == 5 {
3696                 // nodes[1] still wants its final RAA
3697                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3698         } else if messages_delivered == 6 {
3699                 // Everything was delivered...
3700                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3701         }
3702
3703         let events_1 = nodes[1].node.get_and_clear_pending_events();
3704         assert_eq!(events_1.len(), 1);
3705         match events_1[0] {
3706                 Event::PendingHTLCsForwardable { .. } => { },
3707                 _ => panic!("Unexpected event"),
3708         };
3709
3710         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3711         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3712         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3713
3714         nodes[1].node.process_pending_htlc_forwards();
3715
3716         let events_2 = nodes[1].node.get_and_clear_pending_events();
3717         assert_eq!(events_2.len(), 1);
3718         match events_2[0] {
3719                 Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
3720                         assert_eq!(payment_hash_1, *payment_hash);
3721                         assert_eq!(amt, 1000000);
3722                         match &purpose {
3723                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3724                                         assert!(payment_preimage.is_none());
3725                                         assert_eq!(payment_secret_1, *payment_secret);
3726                                 },
3727                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
3728                         }
3729                 },
3730                 _ => panic!("Unexpected event"),
3731         }
3732
3733         nodes[1].node.claim_funds(payment_preimage_1);
3734         check_added_monitors!(nodes[1], 1);
3735
3736         let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3737         assert_eq!(events_3.len(), 1);
3738         let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3739                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3740                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3741                         assert!(updates.update_add_htlcs.is_empty());
3742                         assert!(updates.update_fail_htlcs.is_empty());
3743                         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3744                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3745                         assert!(updates.update_fee.is_none());
3746                         (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3747                 },
3748                 _ => panic!("Unexpected event"),
3749         };
3750
3751         if messages_delivered >= 1 {
3752                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3753
3754                 let events_4 = nodes[0].node.get_and_clear_pending_events();
3755                 assert_eq!(events_4.len(), 1);
3756                 match events_4[0] {
3757                         Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3758                                 assert_eq!(payment_preimage_1, *payment_preimage);
3759                                 assert_eq!(payment_hash_1, *payment_hash);
3760                         },
3761                         _ => panic!("Unexpected event"),
3762                 }
3763
3764                 if messages_delivered >= 2 {
3765                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3766                         check_added_monitors!(nodes[0], 1);
3767                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3768
3769                         if messages_delivered >= 3 {
3770                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3771                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3772                                 check_added_monitors!(nodes[1], 1);
3773
3774                                 if messages_delivered >= 4 {
3775                                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3776                                         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3777                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3778                                         check_added_monitors!(nodes[1], 1);
3779
3780                                         if messages_delivered >= 5 {
3781                                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3782                                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3783                                                 check_added_monitors!(nodes[0], 1);
3784                                         }
3785                                 }
3786                         }
3787                 }
3788         }
3789
3790         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3791         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3792         if messages_delivered < 2 {
3793                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3794                 if messages_delivered < 1 {
3795                         expect_payment_sent!(nodes[0], payment_preimage_1);
3796                 } else {
3797                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3798                 }
3799         } else if messages_delivered == 2 {
3800                 // nodes[0] still wants its RAA + commitment_signed
3801                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3802         } else if messages_delivered == 3 {
3803                 // nodes[0] still wants its commitment_signed
3804                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3805         } else if messages_delivered == 4 {
3806                 // nodes[1] still wants its final RAA
3807                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3808         } else if messages_delivered == 5 {
3809                 // Everything was delivered...
3810                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3811         }
3812
3813         if messages_delivered == 1 || messages_delivered == 2 {
3814                 expect_payment_path_successful!(nodes[0]);
3815         }
3816
3817         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3818         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3819         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3820
3821         if messages_delivered > 2 {
3822                 expect_payment_path_successful!(nodes[0]);
3823         }
3824
3825         // Channel should still work fine...
3826         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3827         let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3828         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3829 }
3830
3831 #[test]
3832 fn test_drop_messages_peer_disconnect_a() {
3833         do_test_drop_messages_peer_disconnect(0, true);
3834         do_test_drop_messages_peer_disconnect(0, false);
3835         do_test_drop_messages_peer_disconnect(1, false);
3836         do_test_drop_messages_peer_disconnect(2, false);
3837 }
3838
3839 #[test]
3840 fn test_drop_messages_peer_disconnect_b() {
3841         do_test_drop_messages_peer_disconnect(3, false);
3842         do_test_drop_messages_peer_disconnect(4, false);
3843         do_test_drop_messages_peer_disconnect(5, false);
3844         do_test_drop_messages_peer_disconnect(6, false);
3845 }
3846
3847 #[test]
3848 fn test_funding_peer_disconnect() {
3849         // Test that we can lock in our funding tx while disconnected
3850         let chanmon_cfgs = create_chanmon_cfgs(2);
3851         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3852         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3853         let persister: test_utils::TestPersister;
3854         let new_chain_monitor: test_utils::TestChainMonitor;
3855         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
3856         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3857         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3858
3859         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3860         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3861
3862         confirm_transaction(&nodes[0], &tx);
3863         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3864         assert!(events_1.is_empty());
3865
3866         reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3867
3868         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3869         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3870
3871         confirm_transaction(&nodes[1], &tx);
3872         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3873         assert!(events_2.is_empty());
3874
3875         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
3876         let as_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
3877         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
3878         let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
3879
3880         // nodes[0] hasn't yet received a funding_locked, so it only sends that on reconnect.
3881         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
3882         let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3883         assert_eq!(events_3.len(), 1);
3884         let as_funding_locked = match events_3[0] {
3885                 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3886                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3887                         msg.clone()
3888                 },
3889                 _ => panic!("Unexpected event {:?}", events_3[0]),
3890         };
3891
3892         // nodes[1] received nodes[0]'s funding_locked on the first reconnect above, so it should send
3893         // announcement_signatures as well as channel_update.
3894         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reestablish);
3895         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3896         assert_eq!(events_4.len(), 3);
3897         let chan_id;
3898         let bs_funding_locked = match events_4[0] {
3899                 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3900                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3901                         chan_id = msg.channel_id;
3902                         msg.clone()
3903                 },
3904                 _ => panic!("Unexpected event {:?}", events_4[0]),
3905         };
3906         let bs_announcement_sigs = match events_4[1] {
3907                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3908                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3909                         msg.clone()
3910                 },
3911                 _ => panic!("Unexpected event {:?}", events_4[1]),
3912         };
3913         match events_4[2] {
3914                 MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } => {
3915                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3916                 },
3917                 _ => panic!("Unexpected event {:?}", events_4[2]),
3918         }
3919
3920         // Re-deliver nodes[0]'s funding_locked, which nodes[1] can safely ignore. It currently
3921         // generates a duplicative private channel_update
3922         nodes[1].node.handle_funding_locked(&nodes[0].node.get_our_node_id(), &as_funding_locked);
3923         let events_5 = nodes[1].node.get_and_clear_pending_msg_events();
3924         assert_eq!(events_5.len(), 1);
3925         match events_5[0] {
3926                 MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } => {
3927                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3928                 },
3929                 _ => panic!("Unexpected event {:?}", events_5[0]),
3930         };
3931
3932         // When we deliver nodes[1]'s funding_locked, however, nodes[0] will generate its
3933         // announcement_signatures.
3934         nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &bs_funding_locked);
3935         let events_6 = nodes[0].node.get_and_clear_pending_msg_events();
3936         assert_eq!(events_6.len(), 1);
3937         let as_announcement_sigs = match events_6[0] {
3938                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3939                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3940                         msg.clone()
3941                 },
3942                 _ => panic!("Unexpected event {:?}", events_6[0]),
3943         };
3944
3945         // When we deliver nodes[1]'s announcement_signatures to nodes[0], nodes[0] should immediately
3946         // broadcast the channel announcement globally, as well as re-send its (now-public)
3947         // channel_update.
3948         nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3949         let events_7 = nodes[0].node.get_and_clear_pending_msg_events();
3950         assert_eq!(events_7.len(), 1);
3951         let (chan_announcement, as_update) = match events_7[0] {
3952                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3953                         (msg.clone(), update_msg.clone())
3954                 },
3955                 _ => panic!("Unexpected event {:?}", events_7[0]),
3956         };
3957
3958         // Finally, deliver nodes[0]'s announcement_signatures to nodes[1] and make sure it creates the
3959         // same channel_announcement.
3960         nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3961         let events_8 = nodes[1].node.get_and_clear_pending_msg_events();
3962         assert_eq!(events_8.len(), 1);
3963         let bs_update = match events_8[0] {
3964                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3965                         assert_eq!(*msg, chan_announcement);
3966                         update_msg.clone()
3967                 },
3968                 _ => panic!("Unexpected event {:?}", events_8[0]),
3969         };
3970
3971         // Provide the channel announcement and public updates to the network graph
3972         nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).unwrap();
3973         nodes[0].net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
3974         nodes[0].net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
3975
3976         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3977         let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3978         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
3979
3980         // Check that after deserialization and reconnection we can still generate an identical
3981         // channel_announcement from the cached signatures.
3982         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3983
3984         let nodes_0_serialized = nodes[0].node.encode();
3985         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
3986         get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
3987
3988         persister = test_utils::TestPersister::new();
3989         let keys_manager = &chanmon_cfgs[0].keys_manager;
3990         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);
3991         nodes[0].chain_monitor = &new_chain_monitor;
3992         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
3993         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
3994                 &mut chan_0_monitor_read, keys_manager).unwrap();
3995         assert!(chan_0_monitor_read.is_empty());
3996
3997         let mut nodes_0_read = &nodes_0_serialized[..];
3998         let (_, nodes_0_deserialized_tmp) = {
3999                 let mut channel_monitors = HashMap::new();
4000                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4001                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4002                         default_config: UserConfig::default(),
4003                         keys_manager,
4004                         fee_estimator: node_cfgs[0].fee_estimator,
4005                         chain_monitor: nodes[0].chain_monitor,
4006                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4007                         logger: nodes[0].logger,
4008                         channel_monitors,
4009                 }).unwrap()
4010         };
4011         nodes_0_deserialized = nodes_0_deserialized_tmp;
4012         assert!(nodes_0_read.is_empty());
4013
4014         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4015         nodes[0].node = &nodes_0_deserialized;
4016         check_added_monitors!(nodes[0], 1);
4017
4018         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4019
4020         // The channel announcement should be re-generated exactly by broadcast_node_announcement.
4021         nodes[0].node.broadcast_node_announcement([0, 0, 0], [0; 32], Vec::new());
4022         let msgs = nodes[0].node.get_and_clear_pending_msg_events();
4023         let mut found_announcement = false;
4024         for event in msgs.iter() {
4025                 match event {
4026                         MessageSendEvent::BroadcastChannelAnnouncement { ref msg, .. } => {
4027                                 if *msg == chan_announcement { found_announcement = true; }
4028                         },
4029                         MessageSendEvent::BroadcastNodeAnnouncement { .. } => {},
4030                         _ => panic!("Unexpected event"),
4031                 }
4032         }
4033         assert!(found_announcement);
4034 }
4035
4036 #[test]
4037 fn test_funding_locked_without_best_block_updated() {
4038         // Previously, if we were offline when a funding transaction was locked in, and then we came
4039         // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
4040         // generate a funding_locked until a later best_block_updated. This tests that we generate the
4041         // funding_locked immediately instead.
4042         let chanmon_cfgs = create_chanmon_cfgs(2);
4043         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4044         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4045         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4046         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
4047
4048         let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
4049
4050         let conf_height = nodes[0].best_block_info().1 + 1;
4051         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
4052         let block_txn = [funding_tx];
4053         let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
4054         let conf_block_header = nodes[0].get_block_header(conf_height);
4055         nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
4056
4057         // Ensure nodes[0] generates a funding_locked after the transactions_confirmed
4058         let as_funding_locked = get_event_msg!(nodes[0], MessageSendEvent::SendFundingLocked, nodes[1].node.get_our_node_id());
4059         nodes[1].node.handle_funding_locked(&nodes[0].node.get_our_node_id(), &as_funding_locked);
4060 }
4061
4062 #[test]
4063 fn test_drop_messages_peer_disconnect_dual_htlc() {
4064         // Test that we can handle reconnecting when both sides of a channel have pending
4065         // commitment_updates when we disconnect.
4066         let chanmon_cfgs = create_chanmon_cfgs(2);
4067         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4068         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4069         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4070         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4071
4072         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4073
4074         // Now try to send a second payment which will fail to send
4075         let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
4076         nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
4077         check_added_monitors!(nodes[0], 1);
4078
4079         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
4080         assert_eq!(events_1.len(), 1);
4081         match events_1[0] {
4082                 MessageSendEvent::UpdateHTLCs { .. } => {},
4083                 _ => panic!("Unexpected event"),
4084         }
4085
4086         assert!(nodes[1].node.claim_funds(payment_preimage_1));
4087         check_added_monitors!(nodes[1], 1);
4088
4089         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
4090         assert_eq!(events_2.len(), 1);
4091         match events_2[0] {
4092                 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, ref update_fee, ref commitment_signed } } => {
4093                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
4094                         assert!(update_add_htlcs.is_empty());
4095                         assert_eq!(update_fulfill_htlcs.len(), 1);
4096                         assert!(update_fail_htlcs.is_empty());
4097                         assert!(update_fail_malformed_htlcs.is_empty());
4098                         assert!(update_fee.is_none());
4099
4100                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
4101                         let events_3 = nodes[0].node.get_and_clear_pending_events();
4102                         assert_eq!(events_3.len(), 1);
4103                         match events_3[0] {
4104                                 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4105                                         assert_eq!(*payment_preimage, payment_preimage_1);
4106                                         assert_eq!(*payment_hash, payment_hash_1);
4107                                 },
4108                                 _ => panic!("Unexpected event"),
4109                         }
4110
4111                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
4112                         let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4113                         // No commitment_signed so get_event_msg's assert(len == 1) passes
4114                         check_added_monitors!(nodes[0], 1);
4115                 },
4116                 _ => panic!("Unexpected event"),
4117         }
4118
4119         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
4120         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4121
4122         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4123         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4124         assert_eq!(reestablish_1.len(), 1);
4125         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4126         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4127         assert_eq!(reestablish_2.len(), 1);
4128
4129         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4130         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4131         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4132         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4133
4134         assert!(as_resp.0.is_none());
4135         assert!(bs_resp.0.is_none());
4136
4137         assert!(bs_resp.1.is_none());
4138         assert!(bs_resp.2.is_none());
4139
4140         assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4141
4142         assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4143         assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4144         assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4145         assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4146         assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4147         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4148         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4149         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4150         // No commitment_signed so get_event_msg's assert(len == 1) passes
4151         check_added_monitors!(nodes[1], 1);
4152
4153         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4154         let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4155         assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4156         assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4157         assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4158         assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4159         assert!(bs_second_commitment_signed.update_fee.is_none());
4160         check_added_monitors!(nodes[1], 1);
4161
4162         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4163         let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4164         assert!(as_commitment_signed.update_add_htlcs.is_empty());
4165         assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4166         assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4167         assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4168         assert!(as_commitment_signed.update_fee.is_none());
4169         check_added_monitors!(nodes[0], 1);
4170
4171         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4172         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4173         // No commitment_signed so get_event_msg's assert(len == 1) passes
4174         check_added_monitors!(nodes[0], 1);
4175
4176         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4177         let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4178         // No commitment_signed so get_event_msg's assert(len == 1) passes
4179         check_added_monitors!(nodes[1], 1);
4180
4181         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4182         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4183         check_added_monitors!(nodes[1], 1);
4184
4185         expect_pending_htlcs_forwardable!(nodes[1]);
4186
4187         let events_5 = nodes[1].node.get_and_clear_pending_events();
4188         assert_eq!(events_5.len(), 1);
4189         match events_5[0] {
4190                 Event::PaymentReceived { ref payment_hash, ref purpose, .. } => {
4191                         assert_eq!(payment_hash_2, *payment_hash);
4192                         match &purpose {
4193                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4194                                         assert!(payment_preimage.is_none());
4195                                         assert_eq!(payment_secret_2, *payment_secret);
4196                                 },
4197                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
4198                         }
4199                 },
4200                 _ => panic!("Unexpected event"),
4201         }
4202
4203         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4204         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4205         check_added_monitors!(nodes[0], 1);
4206
4207         expect_payment_path_successful!(nodes[0]);
4208         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4209 }
4210
4211 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4212         // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4213         // to avoid our counterparty failing the channel.
4214         let chanmon_cfgs = create_chanmon_cfgs(2);
4215         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4216         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4217         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4218
4219         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4220
4221         let our_payment_hash = if send_partial_mpp {
4222                 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4223                 // Use the utility function send_payment_along_path to send the payment with MPP data which
4224                 // indicates there are more HTLCs coming.
4225                 let cur_height = CHAN_CONFIRM_DEPTH + 1; // route_payment calls send_payment, which adds 1 to the current height. So we do the same here to match.
4226                 let payment_id = PaymentId([42; 32]);
4227                 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();
4228                 check_added_monitors!(nodes[0], 1);
4229                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4230                 assert_eq!(events.len(), 1);
4231                 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4232                 // hop should *not* yet generate any PaymentReceived event(s).
4233                 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4234                 our_payment_hash
4235         } else {
4236                 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4237         };
4238
4239         let mut block = Block {
4240                 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
4241                 txdata: vec![],
4242         };
4243         connect_block(&nodes[0], &block);
4244         connect_block(&nodes[1], &block);
4245         let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4246         for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4247                 block.header.prev_blockhash = block.block_hash();
4248                 connect_block(&nodes[0], &block);
4249                 connect_block(&nodes[1], &block);
4250         }
4251
4252         expect_pending_htlcs_forwardable!(nodes[1]);
4253
4254         check_added_monitors!(nodes[1], 1);
4255         let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4256         assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4257         assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4258         assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4259         assert!(htlc_timeout_updates.update_fee.is_none());
4260
4261         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4262         commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4263         // 100_000 msat as u64, followed by the height at which we failed back above
4264         let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
4265         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(block_count - 1));
4266         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4267 }
4268
4269 #[test]
4270 fn test_htlc_timeout() {
4271         do_test_htlc_timeout(true);
4272         do_test_htlc_timeout(false);
4273 }
4274
4275 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4276         // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4277         let chanmon_cfgs = create_chanmon_cfgs(3);
4278         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4279         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4280         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4281         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4282         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4283
4284         // Make sure all nodes are at the same starting height
4285         connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4286         connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4287         connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4288
4289         // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4290         let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4291         {
4292                 nodes[1].node.send_payment(&route, first_payment_hash, &Some(first_payment_secret)).unwrap();
4293         }
4294         assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4295         check_added_monitors!(nodes[1], 1);
4296
4297         // Now attempt to route a second payment, which should be placed in the holding cell
4298         let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4299         let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4300         sending_node.node.send_payment(&route, second_payment_hash, &Some(second_payment_secret)).unwrap();
4301         if forwarded_htlc {
4302                 check_added_monitors!(nodes[0], 1);
4303                 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4304                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4305                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4306                 expect_pending_htlcs_forwardable!(nodes[1]);
4307         }
4308         check_added_monitors!(nodes[1], 0);
4309
4310         connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4311         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4312         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4313         connect_blocks(&nodes[1], 1);
4314
4315         if forwarded_htlc {
4316                 expect_pending_htlcs_forwardable!(nodes[1]);
4317                 check_added_monitors!(nodes[1], 1);
4318                 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4319                 assert_eq!(fail_commit.len(), 1);
4320                 match fail_commit[0] {
4321                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4322                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4323                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4324                         },
4325                         _ => unreachable!(),
4326                 }
4327                 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4328         } else {
4329                 let events = nodes[1].node.get_and_clear_pending_events();
4330                 assert_eq!(events.len(), 2);
4331                 if let Event::PaymentPathFailed { ref payment_hash, .. } = events[0] {
4332                         assert_eq!(*payment_hash, second_payment_hash);
4333                 } else { panic!("Unexpected event"); }
4334                 if let Event::PaymentFailed { ref payment_hash, .. } = events[1] {
4335                         assert_eq!(*payment_hash, second_payment_hash);
4336                 } else { panic!("Unexpected event"); }
4337         }
4338 }
4339
4340 #[test]
4341 fn test_holding_cell_htlc_add_timeouts() {
4342         do_test_holding_cell_htlc_add_timeouts(false);
4343         do_test_holding_cell_htlc_add_timeouts(true);
4344 }
4345
4346 #[test]
4347 fn test_no_txn_manager_serialize_deserialize() {
4348         let chanmon_cfgs = create_chanmon_cfgs(2);
4349         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4350         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4351         let logger: test_utils::TestLogger;
4352         let fee_estimator: test_utils::TestFeeEstimator;
4353         let persister: test_utils::TestPersister;
4354         let new_chain_monitor: test_utils::TestChainMonitor;
4355         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4356         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4357
4358         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
4359
4360         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4361
4362         let nodes_0_serialized = nodes[0].node.encode();
4363         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4364         get_monitor!(nodes[0], OutPoint { txid: tx.txid(), index: 0 }.to_channel_id())
4365                 .write(&mut chan_0_monitor_serialized).unwrap();
4366
4367         logger = test_utils::TestLogger::new();
4368         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4369         persister = test_utils::TestPersister::new();
4370         let keys_manager = &chanmon_cfgs[0].keys_manager;
4371         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4372         nodes[0].chain_monitor = &new_chain_monitor;
4373         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4374         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4375                 &mut chan_0_monitor_read, keys_manager).unwrap();
4376         assert!(chan_0_monitor_read.is_empty());
4377
4378         let mut nodes_0_read = &nodes_0_serialized[..];
4379         let config = UserConfig::default();
4380         let (_, nodes_0_deserialized_tmp) = {
4381                 let mut channel_monitors = HashMap::new();
4382                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4383                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4384                         default_config: config,
4385                         keys_manager,
4386                         fee_estimator: &fee_estimator,
4387                         chain_monitor: nodes[0].chain_monitor,
4388                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4389                         logger: &logger,
4390                         channel_monitors,
4391                 }).unwrap()
4392         };
4393         nodes_0_deserialized = nodes_0_deserialized_tmp;
4394         assert!(nodes_0_read.is_empty());
4395
4396         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4397         nodes[0].node = &nodes_0_deserialized;
4398         assert_eq!(nodes[0].node.list_channels().len(), 1);
4399         check_added_monitors!(nodes[0], 1);
4400
4401         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4402         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4403         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4404         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4405
4406         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4407         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4408         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4409         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4410
4411         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4412         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4413         for node in nodes.iter() {
4414                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4415                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4416                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4417         }
4418
4419         send_payment(&nodes[0], &[&nodes[1]], 1000000);
4420 }
4421
4422 #[test]
4423 fn test_manager_serialize_deserialize_events() {
4424         // This test makes sure the events field in ChannelManager survives de/serialization
4425         let chanmon_cfgs = create_chanmon_cfgs(2);
4426         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4427         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4428         let fee_estimator: test_utils::TestFeeEstimator;
4429         let persister: test_utils::TestPersister;
4430         let logger: test_utils::TestLogger;
4431         let new_chain_monitor: test_utils::TestChainMonitor;
4432         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4433         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4434
4435         // Start creating a channel, but stop right before broadcasting the funding transaction
4436         let channel_value = 100000;
4437         let push_msat = 10001;
4438         let a_flags = InitFeatures::known();
4439         let b_flags = InitFeatures::known();
4440         let node_a = nodes.remove(0);
4441         let node_b = nodes.remove(0);
4442         node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
4443         node_b.node.handle_open_channel(&node_a.node.get_our_node_id(), a_flags, &get_event_msg!(node_a, MessageSendEvent::SendOpenChannel, node_b.node.get_our_node_id()));
4444         node_a.node.handle_accept_channel(&node_b.node.get_our_node_id(), b_flags, &get_event_msg!(node_b, MessageSendEvent::SendAcceptChannel, node_a.node.get_our_node_id()));
4445
4446         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, &node_b.node.get_our_node_id(), channel_value, 42);
4447
4448         node_a.node.funding_transaction_generated(&temporary_channel_id, &node_b.node.get_our_node_id(), tx.clone()).unwrap();
4449         check_added_monitors!(node_a, 0);
4450
4451         node_b.node.handle_funding_created(&node_a.node.get_our_node_id(), &get_event_msg!(node_a, MessageSendEvent::SendFundingCreated, node_b.node.get_our_node_id()));
4452         {
4453                 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
4454                 assert_eq!(added_monitors.len(), 1);
4455                 assert_eq!(added_monitors[0].0, funding_output);
4456                 added_monitors.clear();
4457         }
4458
4459         let bs_funding_signed = get_event_msg!(node_b, MessageSendEvent::SendFundingSigned, node_a.node.get_our_node_id());
4460         node_a.node.handle_funding_signed(&node_b.node.get_our_node_id(), &bs_funding_signed);
4461         {
4462                 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
4463                 assert_eq!(added_monitors.len(), 1);
4464                 assert_eq!(added_monitors[0].0, funding_output);
4465                 added_monitors.clear();
4466         }
4467         // Normally, this is where node_a would broadcast the funding transaction, but the test de/serializes first instead
4468
4469         nodes.push(node_a);
4470         nodes.push(node_b);
4471
4472         // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4473         let nodes_0_serialized = nodes[0].node.encode();
4474         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4475         get_monitor!(nodes[0], bs_funding_signed.channel_id).write(&mut chan_0_monitor_serialized).unwrap();
4476
4477         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4478         logger = test_utils::TestLogger::new();
4479         persister = test_utils::TestPersister::new();
4480         let keys_manager = &chanmon_cfgs[0].keys_manager;
4481         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4482         nodes[0].chain_monitor = &new_chain_monitor;
4483         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4484         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4485                 &mut chan_0_monitor_read, keys_manager).unwrap();
4486         assert!(chan_0_monitor_read.is_empty());
4487
4488         let mut nodes_0_read = &nodes_0_serialized[..];
4489         let config = UserConfig::default();
4490         let (_, nodes_0_deserialized_tmp) = {
4491                 let mut channel_monitors = HashMap::new();
4492                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4493                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4494                         default_config: config,
4495                         keys_manager,
4496                         fee_estimator: &fee_estimator,
4497                         chain_monitor: nodes[0].chain_monitor,
4498                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4499                         logger: &logger,
4500                         channel_monitors,
4501                 }).unwrap()
4502         };
4503         nodes_0_deserialized = nodes_0_deserialized_tmp;
4504         assert!(nodes_0_read.is_empty());
4505
4506         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4507
4508         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4509         nodes[0].node = &nodes_0_deserialized;
4510
4511         // After deserializing, make sure the funding_transaction is still held by the channel manager
4512         let events_4 = nodes[0].node.get_and_clear_pending_events();
4513         assert_eq!(events_4.len(), 0);
4514         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
4515         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
4516
4517         // Make sure the channel is functioning as though the de/serialization never happened
4518         assert_eq!(nodes[0].node.list_channels().len(), 1);
4519         check_added_monitors!(nodes[0], 1);
4520
4521         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4522         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4523         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4524         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4525
4526         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4527         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4528         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4529         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4530
4531         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4532         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4533         for node in nodes.iter() {
4534                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4535                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4536                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4537         }
4538
4539         send_payment(&nodes[0], &[&nodes[1]], 1000000);
4540 }
4541
4542 #[test]
4543 fn test_simple_manager_serialize_deserialize() {
4544         let chanmon_cfgs = create_chanmon_cfgs(2);
4545         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4546         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4547         let logger: test_utils::TestLogger;
4548         let fee_estimator: test_utils::TestFeeEstimator;
4549         let persister: test_utils::TestPersister;
4550         let new_chain_monitor: test_utils::TestChainMonitor;
4551         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4552         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4553         let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
4554
4555         let (our_payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4556         let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4557
4558         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4559
4560         let nodes_0_serialized = nodes[0].node.encode();
4561         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4562         get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
4563
4564         logger = test_utils::TestLogger::new();
4565         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4566         persister = test_utils::TestPersister::new();
4567         let keys_manager = &chanmon_cfgs[0].keys_manager;
4568         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4569         nodes[0].chain_monitor = &new_chain_monitor;
4570         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4571         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4572                 &mut chan_0_monitor_read, keys_manager).unwrap();
4573         assert!(chan_0_monitor_read.is_empty());
4574
4575         let mut nodes_0_read = &nodes_0_serialized[..];
4576         let (_, nodes_0_deserialized_tmp) = {
4577                 let mut channel_monitors = HashMap::new();
4578                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4579                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4580                         default_config: UserConfig::default(),
4581                         keys_manager,
4582                         fee_estimator: &fee_estimator,
4583                         chain_monitor: nodes[0].chain_monitor,
4584                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4585                         logger: &logger,
4586                         channel_monitors,
4587                 }).unwrap()
4588         };
4589         nodes_0_deserialized = nodes_0_deserialized_tmp;
4590         assert!(nodes_0_read.is_empty());
4591
4592         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4593         nodes[0].node = &nodes_0_deserialized;
4594         check_added_monitors!(nodes[0], 1);
4595
4596         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4597
4598         fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4599         claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
4600 }
4601
4602 #[test]
4603 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4604         // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4605         let chanmon_cfgs = create_chanmon_cfgs(4);
4606         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4607         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4608         let logger: test_utils::TestLogger;
4609         let fee_estimator: test_utils::TestFeeEstimator;
4610         let persister: test_utils::TestPersister;
4611         let new_chain_monitor: test_utils::TestChainMonitor;
4612         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4613         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4614         let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
4615         let chan_id_2 = create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known()).2;
4616         let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
4617
4618         let mut node_0_stale_monitors_serialized = Vec::new();
4619         for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4620                 let mut writer = test_utils::TestVecWriter(Vec::new());
4621                 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4622                 node_0_stale_monitors_serialized.push(writer.0);
4623         }
4624
4625         let (our_payment_preimage, _, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4626
4627         // Serialize the ChannelManager here, but the monitor we keep up-to-date
4628         let nodes_0_serialized = nodes[0].node.encode();
4629
4630         route_payment(&nodes[0], &[&nodes[3]], 1000000);
4631         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4632         nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4633         nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4634
4635         // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4636         // nodes[3])
4637         let mut node_0_monitors_serialized = Vec::new();
4638         for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4639                 let mut writer = test_utils::TestVecWriter(Vec::new());
4640                 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4641                 node_0_monitors_serialized.push(writer.0);
4642         }
4643
4644         logger = test_utils::TestLogger::new();
4645         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4646         persister = test_utils::TestPersister::new();
4647         let keys_manager = &chanmon_cfgs[0].keys_manager;
4648         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4649         nodes[0].chain_monitor = &new_chain_monitor;
4650
4651
4652         let mut node_0_stale_monitors = Vec::new();
4653         for serialized in node_0_stale_monitors_serialized.iter() {
4654                 let mut read = &serialized[..];
4655                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4656                 assert!(read.is_empty());
4657                 node_0_stale_monitors.push(monitor);
4658         }
4659
4660         let mut node_0_monitors = Vec::new();
4661         for serialized in node_0_monitors_serialized.iter() {
4662                 let mut read = &serialized[..];
4663                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4664                 assert!(read.is_empty());
4665                 node_0_monitors.push(monitor);
4666         }
4667
4668         let mut nodes_0_read = &nodes_0_serialized[..];
4669         if let Err(msgs::DecodeError::InvalidValue) =
4670                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4671                 default_config: UserConfig::default(),
4672                 keys_manager,
4673                 fee_estimator: &fee_estimator,
4674                 chain_monitor: nodes[0].chain_monitor,
4675                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4676                 logger: &logger,
4677                 channel_monitors: node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4678         }) { } else {
4679                 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4680         };
4681
4682         let mut nodes_0_read = &nodes_0_serialized[..];
4683         let (_, nodes_0_deserialized_tmp) =
4684                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4685                 default_config: UserConfig::default(),
4686                 keys_manager,
4687                 fee_estimator: &fee_estimator,
4688                 chain_monitor: nodes[0].chain_monitor,
4689                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4690                 logger: &logger,
4691                 channel_monitors: node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4692         }).unwrap();
4693         nodes_0_deserialized = nodes_0_deserialized_tmp;
4694         assert!(nodes_0_read.is_empty());
4695
4696         { // Channel close should result in a commitment tx
4697                 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4698                 assert_eq!(txn.len(), 1);
4699                 check_spends!(txn[0], funding_tx);
4700                 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4701         }
4702
4703         for monitor in node_0_monitors.drain(..) {
4704                 assert!(nodes[0].chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor).is_ok());
4705                 check_added_monitors!(nodes[0], 1);
4706         }
4707         nodes[0].node = &nodes_0_deserialized;
4708         check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
4709
4710         // nodes[1] and nodes[2] have no lost state with nodes[0]...
4711         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4712         reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4713         //... and we can even still claim the payment!
4714         claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage);
4715
4716         nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4717         let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4718         nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4719         nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4720         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4721         assert_eq!(msg_events.len(), 1);
4722         if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
4723                 match action {
4724                         &ErrorAction::SendErrorMessage { ref msg } => {
4725                                 assert_eq!(msg.channel_id, channel_id);
4726                         },
4727                         _ => panic!("Unexpected event!"),
4728                 }
4729         }
4730 }
4731
4732 macro_rules! check_spendable_outputs {
4733         ($node: expr, $keysinterface: expr) => {
4734                 {
4735                         let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4736                         let mut txn = Vec::new();
4737                         let mut all_outputs = Vec::new();
4738                         let secp_ctx = Secp256k1::new();
4739                         for event in events.drain(..) {
4740                                 match event {
4741                                         Event::SpendableOutputs { mut outputs } => {
4742                                                 for outp in outputs.drain(..) {
4743                                                         txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4744                                                         all_outputs.push(outp);
4745                                                 }
4746                                         },
4747                                         _ => panic!("Unexpected event"),
4748                                 };
4749                         }
4750                         if all_outputs.len() > 1 {
4751                                 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) {
4752                                         txn.push(tx);
4753                                 }
4754                         }
4755                         txn
4756                 }
4757         }
4758 }
4759
4760 #[test]
4761 fn test_claim_sizeable_push_msat() {
4762         // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4763         let chanmon_cfgs = create_chanmon_cfgs(2);
4764         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4765         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4766         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4767
4768         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000, InitFeatures::known(), InitFeatures::known());
4769         nodes[1].node.force_close_channel(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
4770         check_closed_broadcast!(nodes[1], true);
4771         check_added_monitors!(nodes[1], 1);
4772         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4773         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4774         assert_eq!(node_txn.len(), 1);
4775         check_spends!(node_txn[0], chan.3);
4776         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
4777
4778         mine_transaction(&nodes[1], &node_txn[0]);
4779         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4780
4781         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4782         assert_eq!(spend_txn.len(), 1);
4783         assert_eq!(spend_txn[0].input.len(), 1);
4784         check_spends!(spend_txn[0], node_txn[0]);
4785         assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
4786 }
4787
4788 #[test]
4789 fn test_claim_on_remote_sizeable_push_msat() {
4790         // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4791         // to_remote output is encumbered by a P2WPKH
4792         let chanmon_cfgs = create_chanmon_cfgs(2);
4793         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4794         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4795         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4796
4797         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000, InitFeatures::known(), InitFeatures::known());
4798         nodes[0].node.force_close_channel(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
4799         check_closed_broadcast!(nodes[0], true);
4800         check_added_monitors!(nodes[0], 1);
4801         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4802
4803         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4804         assert_eq!(node_txn.len(), 1);
4805         check_spends!(node_txn[0], chan.3);
4806         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
4807
4808         mine_transaction(&nodes[1], &node_txn[0]);
4809         check_closed_broadcast!(nodes[1], true);
4810         check_added_monitors!(nodes[1], 1);
4811         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4812         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4813
4814         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4815         assert_eq!(spend_txn.len(), 1);
4816         check_spends!(spend_txn[0], node_txn[0]);
4817 }
4818
4819 #[test]
4820 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4821         // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4822         // to_remote output is encumbered by a P2WPKH
4823
4824         let chanmon_cfgs = create_chanmon_cfgs(2);
4825         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4826         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4827         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4828
4829         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::known(), InitFeatures::known());
4830         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4831         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4832         assert_eq!(revoked_local_txn[0].input.len(), 1);
4833         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4834
4835         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4836         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4837         check_closed_broadcast!(nodes[1], true);
4838         check_added_monitors!(nodes[1], 1);
4839         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4840
4841         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4842         mine_transaction(&nodes[1], &node_txn[0]);
4843         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4844
4845         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4846         assert_eq!(spend_txn.len(), 3);
4847         check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4848         check_spends!(spend_txn[1], node_txn[0]);
4849         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4850 }
4851
4852 #[test]
4853 fn test_static_spendable_outputs_preimage_tx() {
4854         let chanmon_cfgs = create_chanmon_cfgs(2);
4855         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4856         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4857         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4858
4859         // Create some initial channels
4860         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4861
4862         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4863
4864         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4865         assert_eq!(commitment_tx[0].input.len(), 1);
4866         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4867
4868         // Settle A's commitment tx on B's chain
4869         assert!(nodes[1].node.claim_funds(payment_preimage));
4870         check_added_monitors!(nodes[1], 1);
4871         mine_transaction(&nodes[1], &commitment_tx[0]);
4872         check_added_monitors!(nodes[1], 1);
4873         let events = nodes[1].node.get_and_clear_pending_msg_events();
4874         match events[0] {
4875                 MessageSendEvent::UpdateHTLCs { .. } => {},
4876                 _ => panic!("Unexpected event"),
4877         }
4878         match events[1] {
4879                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4880                 _ => panic!("Unexepected event"),
4881         }
4882
4883         // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4884         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4885         assert_eq!(node_txn.len(), 3);
4886         check_spends!(node_txn[0], commitment_tx[0]);
4887         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4888         check_spends!(node_txn[1], chan_1.3);
4889         check_spends!(node_txn[2], node_txn[1]);
4890
4891         mine_transaction(&nodes[1], &node_txn[0]);
4892         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4893         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4894
4895         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4896         assert_eq!(spend_txn.len(), 1);
4897         check_spends!(spend_txn[0], node_txn[0]);
4898 }
4899
4900 #[test]
4901 fn test_static_spendable_outputs_timeout_tx() {
4902         let chanmon_cfgs = create_chanmon_cfgs(2);
4903         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4904         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4905         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4906
4907         // Create some initial channels
4908         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4909
4910         // Rebalance the network a bit by relaying one payment through all the channels ...
4911         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4912
4913         let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4914
4915         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4916         assert_eq!(commitment_tx[0].input.len(), 1);
4917         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4918
4919         // Settle A's commitment tx on B' chain
4920         mine_transaction(&nodes[1], &commitment_tx[0]);
4921         check_added_monitors!(nodes[1], 1);
4922         let events = nodes[1].node.get_and_clear_pending_msg_events();
4923         match events[0] {
4924                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4925                 _ => panic!("Unexpected event"),
4926         }
4927         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4928
4929         // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4930         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4931         assert_eq!(node_txn.len(), 2); // ChannelManager : 1 local commitent tx, ChannelMonitor: timeout tx
4932         check_spends!(node_txn[0], chan_1.3.clone());
4933         check_spends!(node_txn[1],  commitment_tx[0].clone());
4934         assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4935
4936         mine_transaction(&nodes[1], &node_txn[1]);
4937         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4938         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4939         expect_payment_failed!(nodes[1], our_payment_hash, true);
4940
4941         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4942         assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4943         check_spends!(spend_txn[0], commitment_tx[0]);
4944         check_spends!(spend_txn[1], node_txn[1]);
4945         check_spends!(spend_txn[2], node_txn[1], commitment_tx[0]); // All outputs
4946 }
4947
4948 #[test]
4949 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4950         let chanmon_cfgs = create_chanmon_cfgs(2);
4951         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4952         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4953         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4954
4955         // Create some initial channels
4956         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4957
4958         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4959         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4960         assert_eq!(revoked_local_txn[0].input.len(), 1);
4961         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4962
4963         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4964
4965         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4966         check_closed_broadcast!(nodes[1], true);
4967         check_added_monitors!(nodes[1], 1);
4968         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4969
4970         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4971         assert_eq!(node_txn.len(), 2);
4972         assert_eq!(node_txn[0].input.len(), 2);
4973         check_spends!(node_txn[0], revoked_local_txn[0]);
4974
4975         mine_transaction(&nodes[1], &node_txn[0]);
4976         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4977
4978         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4979         assert_eq!(spend_txn.len(), 1);
4980         check_spends!(spend_txn[0], node_txn[0]);
4981 }
4982
4983 #[test]
4984 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4985         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4986         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4987         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4988         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4989         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4990
4991         // Create some initial channels
4992         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4993
4994         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4995         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4996         assert_eq!(revoked_local_txn[0].input.len(), 1);
4997         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4998
4999         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
5000
5001         // A will generate HTLC-Timeout from revoked commitment tx
5002         mine_transaction(&nodes[0], &revoked_local_txn[0]);
5003         check_closed_broadcast!(nodes[0], true);
5004         check_added_monitors!(nodes[0], 1);
5005         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5006         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5007
5008         let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5009         assert_eq!(revoked_htlc_txn.len(), 2);
5010         check_spends!(revoked_htlc_txn[0], chan_1.3);
5011         assert_eq!(revoked_htlc_txn[1].input.len(), 1);
5012         assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5013         check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
5014         assert_ne!(revoked_htlc_txn[1].lock_time, 0); // HTLC-Timeout
5015
5016         // B will generate justice tx from A's revoked commitment/HTLC tx
5017         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5018         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[1].clone()] });
5019         check_closed_broadcast!(nodes[1], true);
5020         check_added_monitors!(nodes[1], 1);
5021         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5022
5023         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5024         assert_eq!(node_txn.len(), 3); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs, ChannelManager: local commitment tx
5025         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5026         // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
5027         // transactions next...
5028         assert_eq!(node_txn[0].input.len(), 3);
5029         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[1]);
5030
5031         assert_eq!(node_txn[1].input.len(), 2);
5032         check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[1]);
5033         if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[1].txid() {
5034                 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
5035         } else {
5036                 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[1].txid());
5037                 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[1].input[0].previous_output);
5038         }
5039
5040         assert_eq!(node_txn[2].input.len(), 1);
5041         check_spends!(node_txn[2], chan_1.3);
5042
5043         mine_transaction(&nodes[1], &node_txn[1]);
5044         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5045
5046         // Check B's ChannelMonitor was able to generate the right spendable output descriptor
5047         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5048         assert_eq!(spend_txn.len(), 1);
5049         assert_eq!(spend_txn[0].input.len(), 1);
5050         check_spends!(spend_txn[0], node_txn[1]);
5051 }
5052
5053 #[test]
5054 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
5055         let mut chanmon_cfgs = create_chanmon_cfgs(2);
5056         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
5057         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5058         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5059         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5060
5061         // Create some initial channels
5062         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5063
5064         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5065         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5066         assert_eq!(revoked_local_txn[0].input.len(), 1);
5067         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5068
5069         // The to-be-revoked commitment tx should have one HTLC and one to_remote output
5070         assert_eq!(revoked_local_txn[0].output.len(), 2);
5071
5072         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
5073
5074         // B will generate HTLC-Success from revoked commitment tx
5075         mine_transaction(&nodes[1], &revoked_local_txn[0]);
5076         check_closed_broadcast!(nodes[1], true);
5077         check_added_monitors!(nodes[1], 1);
5078         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5079         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5080
5081         assert_eq!(revoked_htlc_txn.len(), 2);
5082         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
5083         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5084         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
5085
5086         // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
5087         let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
5088         assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
5089
5090         // A will generate justice tx from B's revoked commitment/HTLC tx
5091         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5092         connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
5093         check_closed_broadcast!(nodes[0], true);
5094         check_added_monitors!(nodes[0], 1);
5095         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5096
5097         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5098         assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
5099
5100         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5101         // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
5102         // transactions next...
5103         assert_eq!(node_txn[0].input.len(), 2);
5104         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
5105         if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
5106                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5107         } else {
5108                 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
5109                 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5110         }
5111
5112         assert_eq!(node_txn[1].input.len(), 1);
5113         check_spends!(node_txn[1], revoked_htlc_txn[0]);
5114
5115         check_spends!(node_txn[2], chan_1.3);
5116
5117         mine_transaction(&nodes[0], &node_txn[1]);
5118         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5119
5120         // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
5121         // didn't try to generate any new transactions.
5122
5123         // Check A's ChannelMonitor was able to generate the right spendable output descriptor
5124         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5125         assert_eq!(spend_txn.len(), 3);
5126         assert_eq!(spend_txn[0].input.len(), 1);
5127         check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
5128         assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5129         check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
5130         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
5131 }
5132
5133 #[test]
5134 fn test_onchain_to_onchain_claim() {
5135         // Test that in case of channel closure, we detect the state of output and claim HTLC
5136         // on downstream peer's remote commitment tx.
5137         // First, have C claim an HTLC against its own latest commitment transaction.
5138         // Then, broadcast these to B, which should update the monitor downstream on the A<->B
5139         // channel.
5140         // Finally, check that B will claim the HTLC output if A's latest commitment transaction
5141         // gets broadcast.
5142
5143         let chanmon_cfgs = create_chanmon_cfgs(3);
5144         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5145         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5146         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5147
5148         // Create some initial channels
5149         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5150         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5151
5152         // Ensure all nodes are at the same height
5153         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5154         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5155         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5156         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5157
5158         // Rebalance the network a bit by relaying one payment through all the channels ...
5159         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5160         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5161
5162         let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
5163         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
5164         check_spends!(commitment_tx[0], chan_2.3);
5165         nodes[2].node.claim_funds(payment_preimage);
5166         check_added_monitors!(nodes[2], 1);
5167         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5168         assert!(updates.update_add_htlcs.is_empty());
5169         assert!(updates.update_fail_htlcs.is_empty());
5170         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5171         assert!(updates.update_fail_malformed_htlcs.is_empty());
5172
5173         mine_transaction(&nodes[2], &commitment_tx[0]);
5174         check_closed_broadcast!(nodes[2], true);
5175         check_added_monitors!(nodes[2], 1);
5176         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5177
5178         let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
5179         assert_eq!(c_txn.len(), 3);
5180         assert_eq!(c_txn[0], c_txn[2]);
5181         assert_eq!(commitment_tx[0], c_txn[1]);
5182         check_spends!(c_txn[1], chan_2.3);
5183         check_spends!(c_txn[2], c_txn[1]);
5184         assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
5185         assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5186         assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5187         assert_eq!(c_txn[0].lock_time, 0); // Success tx
5188
5189         // 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
5190         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
5191         connect_block(&nodes[1], &Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]});
5192         check_added_monitors!(nodes[1], 1);
5193         let events = nodes[1].node.get_and_clear_pending_events();
5194         assert_eq!(events.len(), 2);
5195         match events[0] {
5196                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5197                 _ => panic!("Unexpected event"),
5198         }
5199         match events[1] {
5200                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
5201                         assert_eq!(fee_earned_msat, Some(1000));
5202                         assert_eq!(prev_channel_id, Some(chan_1.2));
5203                         assert_eq!(claim_from_onchain_tx, true);
5204                         assert_eq!(next_channel_id, Some(chan_2.2));
5205                 },
5206                 _ => panic!("Unexpected event"),
5207         }
5208         {
5209                 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5210                 // ChannelMonitor: claim tx
5211                 assert_eq!(b_txn.len(), 1);
5212                 check_spends!(b_txn[0], chan_2.3); // B local commitment tx, issued by ChannelManager
5213                 b_txn.clear();
5214         }
5215         check_added_monitors!(nodes[1], 1);
5216         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5217         assert_eq!(msg_events.len(), 3);
5218         match msg_events[0] {
5219                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5220                 _ => panic!("Unexpected event"),
5221         }
5222         match msg_events[1] {
5223                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
5224                 _ => panic!("Unexpected event"),
5225         }
5226         match msg_events[2] {
5227                 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, .. } } => {
5228                         assert!(update_add_htlcs.is_empty());
5229                         assert!(update_fail_htlcs.is_empty());
5230                         assert_eq!(update_fulfill_htlcs.len(), 1);
5231                         assert!(update_fail_malformed_htlcs.is_empty());
5232                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5233                 },
5234                 _ => panic!("Unexpected event"),
5235         };
5236         // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
5237         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5238         mine_transaction(&nodes[1], &commitment_tx[0]);
5239         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5240         let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5241         // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
5242         assert_eq!(b_txn.len(), 3);
5243         check_spends!(b_txn[1], chan_1.3);
5244         check_spends!(b_txn[2], b_txn[1]);
5245         check_spends!(b_txn[0], commitment_tx[0]);
5246         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5247         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5248         assert_eq!(b_txn[0].lock_time, 0); // Success tx
5249
5250         check_closed_broadcast!(nodes[1], true);
5251         check_added_monitors!(nodes[1], 1);
5252 }
5253
5254 #[test]
5255 fn test_duplicate_payment_hash_one_failure_one_success() {
5256         // Topology : A --> B --> C --> D
5257         // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5258         // Note that because C will refuse to generate two payment secrets for the same payment hash,
5259         // we forward one of the payments onwards to D.
5260         let chanmon_cfgs = create_chanmon_cfgs(4);
5261         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
5262         // When this test was written, the default base fee floated based on the HTLC count.
5263         // It is now fixed, so we simply set the fee to the expected value here.
5264         let mut config = test_default_channel_config();
5265         config.channel_options.forwarding_fee_base_msat = 196;
5266         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
5267                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5268         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
5269
5270         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5271         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5272         create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5273
5274         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5275         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5276         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5277         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5278         connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
5279
5280         let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
5281
5282         let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200).unwrap();
5283         // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
5284         // script push size limit so that the below script length checks match
5285         // ACCEPTED_HTLC_SCRIPT_WEIGHT.
5286         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id())
5287                 .with_features(InvoiceFeatures::known());
5288         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 900000, TEST_FINAL_CLTV - 40);
5289         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 900000, duplicate_payment_hash, payment_secret);
5290
5291         let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5292         assert_eq!(commitment_txn[0].input.len(), 1);
5293         check_spends!(commitment_txn[0], chan_2.3);
5294
5295         mine_transaction(&nodes[1], &commitment_txn[0]);
5296         check_closed_broadcast!(nodes[1], true);
5297         check_added_monitors!(nodes[1], 1);
5298         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5299         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
5300
5301         let htlc_timeout_tx;
5302         { // Extract one of the two HTLC-Timeout transaction
5303                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5304                 // ChannelMonitor: timeout tx * 2-or-3, ChannelManager: local commitment tx
5305                 assert!(node_txn.len() == 4 || node_txn.len() == 3);
5306                 check_spends!(node_txn[0], chan_2.3);
5307
5308                 check_spends!(node_txn[1], commitment_txn[0]);
5309                 assert_eq!(node_txn[1].input.len(), 1);
5310
5311                 if node_txn.len() > 3 {
5312                         check_spends!(node_txn[2], commitment_txn[0]);
5313                         assert_eq!(node_txn[2].input.len(), 1);
5314                         assert_eq!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
5315
5316                         check_spends!(node_txn[3], commitment_txn[0]);
5317                         assert_ne!(node_txn[1].input[0].previous_output, node_txn[3].input[0].previous_output);
5318                 } else {
5319                         check_spends!(node_txn[2], commitment_txn[0]);
5320                         assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
5321                 }
5322
5323                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5324                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5325                 if node_txn.len() > 3 {
5326                         assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5327                 }
5328                 htlc_timeout_tx = node_txn[1].clone();
5329         }
5330
5331         nodes[2].node.claim_funds(our_payment_preimage);
5332         mine_transaction(&nodes[2], &commitment_txn[0]);
5333         check_added_monitors!(nodes[2], 2);
5334         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5335         let events = nodes[2].node.get_and_clear_pending_msg_events();
5336         match events[0] {
5337                 MessageSendEvent::UpdateHTLCs { .. } => {},
5338                 _ => panic!("Unexpected event"),
5339         }
5340         match events[1] {
5341                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5342                 _ => panic!("Unexepected event"),
5343         }
5344         let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5345         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)
5346         check_spends!(htlc_success_txn[0], commitment_txn[0]);
5347         check_spends!(htlc_success_txn[1], commitment_txn[0]);
5348         assert_eq!(htlc_success_txn[0].input.len(), 1);
5349         assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5350         assert_eq!(htlc_success_txn[1].input.len(), 1);
5351         assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5352         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
5353         assert_eq!(htlc_success_txn[2], commitment_txn[0]);
5354         assert_eq!(htlc_success_txn[3], htlc_success_txn[0]);
5355         assert_eq!(htlc_success_txn[4], htlc_success_txn[1]);
5356         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
5357
5358         mine_transaction(&nodes[1], &htlc_timeout_tx);
5359         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5360         expect_pending_htlcs_forwardable!(nodes[1]);
5361         let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5362         assert!(htlc_updates.update_add_htlcs.is_empty());
5363         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5364         let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
5365         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5366         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5367         check_added_monitors!(nodes[1], 1);
5368
5369         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5370         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5371         {
5372                 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5373         }
5374         expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
5375
5376         // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5377         // Note that the fee paid is effectively double as the HTLC value (including the nodes[1] fee
5378         // and nodes[2] fee) is rounded down and then claimed in full.
5379         mine_transaction(&nodes[1], &htlc_success_txn[0]);
5380         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196*2), true, true);
5381         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5382         assert!(updates.update_add_htlcs.is_empty());
5383         assert!(updates.update_fail_htlcs.is_empty());
5384         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5385         assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
5386         assert!(updates.update_fail_malformed_htlcs.is_empty());
5387         check_added_monitors!(nodes[1], 1);
5388
5389         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5390         commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5391
5392         let events = nodes[0].node.get_and_clear_pending_events();
5393         match events[0] {
5394                 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
5395                         assert_eq!(*payment_preimage, our_payment_preimage);
5396                         assert_eq!(*payment_hash, duplicate_payment_hash);
5397                 }
5398                 _ => panic!("Unexpected event"),
5399         }
5400 }
5401
5402 #[test]
5403 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5404         let chanmon_cfgs = create_chanmon_cfgs(2);
5405         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5406         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5407         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5408
5409         // Create some initial channels
5410         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5411
5412         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
5413         let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5414         assert_eq!(local_txn.len(), 1);
5415         assert_eq!(local_txn[0].input.len(), 1);
5416         check_spends!(local_txn[0], chan_1.3);
5417
5418         // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5419         nodes[1].node.claim_funds(payment_preimage);
5420         check_added_monitors!(nodes[1], 1);
5421         mine_transaction(&nodes[1], &local_txn[0]);
5422         check_added_monitors!(nodes[1], 1);
5423         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5424         let events = nodes[1].node.get_and_clear_pending_msg_events();
5425         match events[0] {
5426                 MessageSendEvent::UpdateHTLCs { .. } => {},
5427                 _ => panic!("Unexpected event"),
5428         }
5429         match events[1] {
5430                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5431                 _ => panic!("Unexepected event"),
5432         }
5433         let node_tx = {
5434                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5435                 assert_eq!(node_txn.len(), 3);
5436                 assert_eq!(node_txn[0], node_txn[2]);
5437                 assert_eq!(node_txn[1], local_txn[0]);
5438                 assert_eq!(node_txn[0].input.len(), 1);
5439                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5440                 check_spends!(node_txn[0], local_txn[0]);
5441                 node_txn[0].clone()
5442         };
5443
5444         mine_transaction(&nodes[1], &node_tx);
5445         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
5446
5447         // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5448         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5449         assert_eq!(spend_txn.len(), 1);
5450         assert_eq!(spend_txn[0].input.len(), 1);
5451         check_spends!(spend_txn[0], node_tx);
5452         assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5453 }
5454
5455 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5456         // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5457         // unrevoked commitment transaction.
5458         // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5459         // a remote RAA before they could be failed backwards (and combinations thereof).
5460         // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5461         // use the same payment hashes.
5462         // Thus, we use a six-node network:
5463         //
5464         // A \         / E
5465         //    - C - D -
5466         // B /         \ F
5467         // And test where C fails back to A/B when D announces its latest commitment transaction
5468         let chanmon_cfgs = create_chanmon_cfgs(6);
5469         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5470         // When this test was written, the default base fee floated based on the HTLC count.
5471         // It is now fixed, so we simply set the fee to the expected value here.
5472         let mut config = test_default_channel_config();
5473         config.channel_options.forwarding_fee_base_msat = 196;
5474         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
5475                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5476         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5477
5478         create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5479         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5480         let chan = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5481         create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
5482         create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
5483
5484         // Rebalance and check output sanity...
5485         send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
5486         send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
5487         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 2);
5488
5489         let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
5490         // 0th HTLC:
5491         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
5492         // 1st HTLC:
5493         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
5494         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5495         // 2nd HTLC:
5496         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
5497         // 3rd HTLC:
5498         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
5499         // 4th HTLC:
5500         let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5501         // 5th HTLC:
5502         let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5503         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5504         // 6th HTLC:
5505         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());
5506         // 7th HTLC:
5507         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());
5508
5509         // 8th HTLC:
5510         let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5511         // 9th HTLC:
5512         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5513         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
5514
5515         // 10th HTLC:
5516         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
5517         // 11th HTLC:
5518         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5519         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());
5520
5521         // Double-check that six of the new HTLC were added
5522         // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5523         // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5524         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2).len(), 1);
5525         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 8);
5526
5527         // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5528         // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5529         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_1));
5530         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_3));
5531         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_5));
5532         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_6));
5533         check_added_monitors!(nodes[4], 0);
5534         expect_pending_htlcs_forwardable!(nodes[4]);
5535         check_added_monitors!(nodes[4], 1);
5536
5537         let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5538         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5539         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5540         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5541         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5542         commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5543
5544         // Fail 3rd below-dust and 7th above-dust HTLCs
5545         assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_2));
5546         assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_4));
5547         check_added_monitors!(nodes[5], 0);
5548         expect_pending_htlcs_forwardable!(nodes[5]);
5549         check_added_monitors!(nodes[5], 1);
5550
5551         let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5552         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5553         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5554         commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5555
5556         let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5557
5558         expect_pending_htlcs_forwardable!(nodes[3]);
5559         check_added_monitors!(nodes[3], 1);
5560         let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5561         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5562         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5563         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5564         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5565         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5566         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5567         if deliver_last_raa {
5568                 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5569         } else {
5570                 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5571         }
5572
5573         // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5574         // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5575         // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5576         // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5577         //
5578         // We now broadcast the latest commitment transaction, which *should* result in failures for
5579         // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5580         // the non-broadcast above-dust HTLCs.
5581         //
5582         // Alternatively, we may broadcast the previous commitment transaction, which should only
5583         // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5584         let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5585
5586         if announce_latest {
5587                 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5588         } else {
5589                 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5590         }
5591         let events = nodes[2].node.get_and_clear_pending_events();
5592         let close_event = if deliver_last_raa {
5593                 assert_eq!(events.len(), 2);
5594                 events[1].clone()
5595         } else {
5596                 assert_eq!(events.len(), 1);
5597                 events[0].clone()
5598         };
5599         match close_event {
5600                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5601                 _ => panic!("Unexpected event"),
5602         }
5603
5604         connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5605         check_closed_broadcast!(nodes[2], true);
5606         if deliver_last_raa {
5607                 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5608         } else {
5609                 expect_pending_htlcs_forwardable!(nodes[2]);
5610         }
5611         check_added_monitors!(nodes[2], 3);
5612
5613         let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5614         assert_eq!(cs_msgs.len(), 2);
5615         let mut a_done = false;
5616         for msg in cs_msgs {
5617                 match msg {
5618                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5619                                 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5620                                 // should be failed-backwards here.
5621                                 let target = if *node_id == nodes[0].node.get_our_node_id() {
5622                                         // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5623                                         for htlc in &updates.update_fail_htlcs {
5624                                                 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 });
5625                                         }
5626                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5627                                         assert!(!a_done);
5628                                         a_done = true;
5629                                         &nodes[0]
5630                                 } else {
5631                                         // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5632                                         for htlc in &updates.update_fail_htlcs {
5633                                                 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5634                                         }
5635                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5636                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5637                                         &nodes[1]
5638                                 };
5639                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5640                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5641                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5642                                 if announce_latest {
5643                                         target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5644                                         if *node_id == nodes[0].node.get_our_node_id() {
5645                                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5646                                         }
5647                                 }
5648                                 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5649                         },
5650                         _ => panic!("Unexpected event"),
5651                 }
5652         }
5653
5654         let as_events = nodes[0].node.get_and_clear_pending_events();
5655         assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5656         let mut as_failds = HashSet::new();
5657         let mut as_updates = 0;
5658         for event in as_events.iter() {
5659                 if let &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5660                         assert!(as_failds.insert(*payment_hash));
5661                         if *payment_hash != payment_hash_2 {
5662                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5663                         } else {
5664                                 assert!(!rejected_by_dest);
5665                         }
5666                         if network_update.is_some() {
5667                                 as_updates += 1;
5668                         }
5669                 } else { panic!("Unexpected event"); }
5670         }
5671         assert!(as_failds.contains(&payment_hash_1));
5672         assert!(as_failds.contains(&payment_hash_2));
5673         if announce_latest {
5674                 assert!(as_failds.contains(&payment_hash_3));
5675                 assert!(as_failds.contains(&payment_hash_5));
5676         }
5677         assert!(as_failds.contains(&payment_hash_6));
5678
5679         let bs_events = nodes[1].node.get_and_clear_pending_events();
5680         assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5681         let mut bs_failds = HashSet::new();
5682         let mut bs_updates = 0;
5683         for event in bs_events.iter() {
5684                 if let &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5685                         assert!(bs_failds.insert(*payment_hash));
5686                         if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5687                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5688                         } else {
5689                                 assert!(!rejected_by_dest);
5690                         }
5691                         if network_update.is_some() {
5692                                 bs_updates += 1;
5693                         }
5694                 } else { panic!("Unexpected event"); }
5695         }
5696         assert!(bs_failds.contains(&payment_hash_1));
5697         assert!(bs_failds.contains(&payment_hash_2));
5698         if announce_latest {
5699                 assert!(bs_failds.contains(&payment_hash_4));
5700         }
5701         assert!(bs_failds.contains(&payment_hash_5));
5702
5703         // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5704         // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5705         // unknown-preimage-etc, B should have gotten 2. Thus, in the
5706         // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5707         assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5708         assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5709 }
5710
5711 #[test]
5712 fn test_fail_backwards_latest_remote_announce_a() {
5713         do_test_fail_backwards_unrevoked_remote_announce(false, true);
5714 }
5715
5716 #[test]
5717 fn test_fail_backwards_latest_remote_announce_b() {
5718         do_test_fail_backwards_unrevoked_remote_announce(true, true);
5719 }
5720
5721 #[test]
5722 fn test_fail_backwards_previous_remote_announce() {
5723         do_test_fail_backwards_unrevoked_remote_announce(false, false);
5724         // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5725         // tested for in test_commitment_revoked_fail_backward_exhaustive()
5726 }
5727
5728 #[test]
5729 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5730         let chanmon_cfgs = create_chanmon_cfgs(2);
5731         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5732         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5733         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5734
5735         // Create some initial channels
5736         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5737
5738         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5739         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5740         assert_eq!(local_txn[0].input.len(), 1);
5741         check_spends!(local_txn[0], chan_1.3);
5742
5743         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5744         mine_transaction(&nodes[0], &local_txn[0]);
5745         check_closed_broadcast!(nodes[0], true);
5746         check_added_monitors!(nodes[0], 1);
5747         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5748         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5749
5750         let htlc_timeout = {
5751                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5752                 assert_eq!(node_txn.len(), 2);
5753                 check_spends!(node_txn[0], chan_1.3);
5754                 assert_eq!(node_txn[1].input.len(), 1);
5755                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5756                 check_spends!(node_txn[1], local_txn[0]);
5757                 node_txn[1].clone()
5758         };
5759
5760         mine_transaction(&nodes[0], &htlc_timeout);
5761         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5762         expect_payment_failed!(nodes[0], our_payment_hash, true);
5763
5764         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5765         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5766         assert_eq!(spend_txn.len(), 3);
5767         check_spends!(spend_txn[0], local_txn[0]);
5768         assert_eq!(spend_txn[1].input.len(), 1);
5769         check_spends!(spend_txn[1], htlc_timeout);
5770         assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5771         assert_eq!(spend_txn[2].input.len(), 2);
5772         check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5773         assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5774                 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5775 }
5776
5777 #[test]
5778 fn test_key_derivation_params() {
5779         // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5780         // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5781         // let us re-derive the channel key set to then derive a delayed_payment_key.
5782
5783         let chanmon_cfgs = create_chanmon_cfgs(3);
5784
5785         // We manually create the node configuration to backup the seed.
5786         let seed = [42; 32];
5787         let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5788         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);
5789         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() };
5790         let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5791         node_cfgs.remove(0);
5792         node_cfgs.insert(0, node);
5793
5794         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5795         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5796
5797         // Create some initial channels
5798         // Create a dummy channel to advance index by one and thus test re-derivation correctness
5799         // for node 0
5800         let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5801         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5802         assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5803
5804         // Ensure all nodes are at the same height
5805         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5806         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5807         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5808         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5809
5810         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5811         let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5812         let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5813         assert_eq!(local_txn_1[0].input.len(), 1);
5814         check_spends!(local_txn_1[0], chan_1.3);
5815
5816         // We check funding pubkey are unique
5817         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]));
5818         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]));
5819         if from_0_funding_key_0 == from_1_funding_key_0
5820             || from_0_funding_key_0 == from_1_funding_key_1
5821             || from_0_funding_key_1 == from_1_funding_key_0
5822             || from_0_funding_key_1 == from_1_funding_key_1 {
5823                 panic!("Funding pubkeys aren't unique");
5824         }
5825
5826         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5827         mine_transaction(&nodes[0], &local_txn_1[0]);
5828         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5829         check_closed_broadcast!(nodes[0], true);
5830         check_added_monitors!(nodes[0], 1);
5831         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5832
5833         let htlc_timeout = {
5834                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5835                 assert_eq!(node_txn[1].input.len(), 1);
5836                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5837                 check_spends!(node_txn[1], local_txn_1[0]);
5838                 node_txn[1].clone()
5839         };
5840
5841         mine_transaction(&nodes[0], &htlc_timeout);
5842         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5843         expect_payment_failed!(nodes[0], our_payment_hash, true);
5844
5845         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5846         let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5847         let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5848         assert_eq!(spend_txn.len(), 3);
5849         check_spends!(spend_txn[0], local_txn_1[0]);
5850         assert_eq!(spend_txn[1].input.len(), 1);
5851         check_spends!(spend_txn[1], htlc_timeout);
5852         assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5853         assert_eq!(spend_txn[2].input.len(), 2);
5854         check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5855         assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5856                 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5857 }
5858
5859 #[test]
5860 fn test_static_output_closing_tx() {
5861         let chanmon_cfgs = create_chanmon_cfgs(2);
5862         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5863         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5864         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5865
5866         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5867
5868         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5869         let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5870
5871         mine_transaction(&nodes[0], &closing_tx);
5872         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5873         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5874
5875         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5876         assert_eq!(spend_txn.len(), 1);
5877         check_spends!(spend_txn[0], closing_tx);
5878
5879         mine_transaction(&nodes[1], &closing_tx);
5880         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5881         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5882
5883         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5884         assert_eq!(spend_txn.len(), 1);
5885         check_spends!(spend_txn[0], closing_tx);
5886 }
5887
5888 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5889         let chanmon_cfgs = create_chanmon_cfgs(2);
5890         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5891         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5892         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5893         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5894
5895         let (payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3000000 });
5896
5897         // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5898         // present in B's local commitment transaction, but none of A's commitment transactions.
5899         assert!(nodes[1].node.claim_funds(payment_preimage));
5900         check_added_monitors!(nodes[1], 1);
5901
5902         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5903         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5904         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
5905
5906         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5907         check_added_monitors!(nodes[0], 1);
5908         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5909         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5910         check_added_monitors!(nodes[1], 1);
5911
5912         let starting_block = nodes[1].best_block_info();
5913         let mut block = Block {
5914                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5915                 txdata: vec![],
5916         };
5917         for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5918                 connect_block(&nodes[1], &block);
5919                 block.header.prev_blockhash = block.block_hash();
5920         }
5921         test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5922         check_closed_broadcast!(nodes[1], true);
5923         check_added_monitors!(nodes[1], 1);
5924         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5925 }
5926
5927 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5928         let chanmon_cfgs = create_chanmon_cfgs(2);
5929         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5930         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5931         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5932         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5933
5934         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5935         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
5936         check_added_monitors!(nodes[0], 1);
5937
5938         let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5939
5940         // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5941         // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5942         // to "time out" the HTLC.
5943
5944         let starting_block = nodes[1].best_block_info();
5945         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5946
5947         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5948                 connect_block(&nodes[0], &Block { header, txdata: Vec::new()});
5949                 header.prev_blockhash = header.block_hash();
5950         }
5951         test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5952         check_closed_broadcast!(nodes[0], true);
5953         check_added_monitors!(nodes[0], 1);
5954         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5955 }
5956
5957 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5958         let chanmon_cfgs = create_chanmon_cfgs(3);
5959         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5960         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5961         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5962         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5963
5964         // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5965         // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5966         // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5967         // actually revoked.
5968         let htlc_value = if use_dust { 50000 } else { 3000000 };
5969         let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5970         assert!(nodes[1].node.fail_htlc_backwards(&our_payment_hash));
5971         expect_pending_htlcs_forwardable!(nodes[1]);
5972         check_added_monitors!(nodes[1], 1);
5973
5974         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5975         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5976         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5977         check_added_monitors!(nodes[0], 1);
5978         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5979         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5980         check_added_monitors!(nodes[1], 1);
5981         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5982         check_added_monitors!(nodes[1], 1);
5983         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5984
5985         if check_revoke_no_close {
5986                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5987                 check_added_monitors!(nodes[0], 1);
5988         }
5989
5990         let starting_block = nodes[1].best_block_info();
5991         let mut block = Block {
5992                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5993                 txdata: vec![],
5994         };
5995         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5996                 connect_block(&nodes[0], &block);
5997                 block.header.prev_blockhash = block.block_hash();
5998         }
5999         if !check_revoke_no_close {
6000                 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
6001                 check_closed_broadcast!(nodes[0], true);
6002                 check_added_monitors!(nodes[0], 1);
6003                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6004         } else {
6005                 let events = nodes[0].node.get_and_clear_pending_events();
6006                 assert_eq!(events.len(), 2);
6007                 if let Event::PaymentPathFailed { ref payment_hash, .. } = events[0] {
6008                         assert_eq!(*payment_hash, our_payment_hash);
6009                 } else { panic!("Unexpected event"); }
6010                 if let Event::PaymentFailed { ref payment_hash, .. } = events[1] {
6011                         assert_eq!(*payment_hash, our_payment_hash);
6012                 } else { panic!("Unexpected event"); }
6013         }
6014 }
6015
6016 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
6017 // There are only a few cases to test here:
6018 //  * its not really normative behavior, but we test that below-dust HTLCs "included" in
6019 //    broadcastable commitment transactions result in channel closure,
6020 //  * its included in an unrevoked-but-previous remote commitment transaction,
6021 //  * its included in the latest remote or local commitment transactions.
6022 // We test each of the three possible commitment transactions individually and use both dust and
6023 // non-dust HTLCs.
6024 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
6025 // assume they are handled the same across all six cases, as both outbound and inbound failures are
6026 // tested for at least one of the cases in other tests.
6027 #[test]
6028 fn htlc_claim_single_commitment_only_a() {
6029         do_htlc_claim_local_commitment_only(true);
6030         do_htlc_claim_local_commitment_only(false);
6031
6032         do_htlc_claim_current_remote_commitment_only(true);
6033         do_htlc_claim_current_remote_commitment_only(false);
6034 }
6035
6036 #[test]
6037 fn htlc_claim_single_commitment_only_b() {
6038         do_htlc_claim_previous_remote_commitment_only(true, false);
6039         do_htlc_claim_previous_remote_commitment_only(false, false);
6040         do_htlc_claim_previous_remote_commitment_only(true, true);
6041         do_htlc_claim_previous_remote_commitment_only(false, true);
6042 }
6043
6044 #[test]
6045 #[should_panic]
6046 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
6047         let chanmon_cfgs = create_chanmon_cfgs(2);
6048         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6049         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6050         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6051         // Force duplicate randomness for every get-random call
6052         for node in nodes.iter() {
6053                 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
6054         }
6055
6056         // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
6057         let channel_value_satoshis=10000;
6058         let push_msat=10001;
6059         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
6060         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6061         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
6062         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
6063
6064         // Create a second channel with the same random values. This used to panic due to a colliding
6065         // channel_id, but now panics due to a colliding outbound SCID alias.
6066         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6067 }
6068
6069 #[test]
6070 fn bolt2_open_channel_sending_node_checks_part2() {
6071         let chanmon_cfgs = create_chanmon_cfgs(2);
6072         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6073         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6074         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6075
6076         // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
6077         let channel_value_satoshis=2^24;
6078         let push_msat=10001;
6079         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6080
6081         // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
6082         let channel_value_satoshis=10000;
6083         // Test when push_msat is equal to 1000 * funding_satoshis.
6084         let push_msat=1000*channel_value_satoshis+1;
6085         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6086
6087         // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
6088         let channel_value_satoshis=10000;
6089         let push_msat=10001;
6090         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
6091         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6092         assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
6093
6094         // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
6095         // 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
6096         assert!(node0_to_1_send_open_channel.channel_flags<=1);
6097
6098         // 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.
6099         assert!(BREAKDOWN_TIMEOUT>0);
6100         assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
6101
6102         // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
6103         let chain_hash=genesis_block(Network::Testnet).header.block_hash();
6104         assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
6105
6106         // 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.
6107         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
6108         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
6109         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
6110         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
6111         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
6112 }
6113
6114 #[test]
6115 fn bolt2_open_channel_sane_dust_limit() {
6116         let chanmon_cfgs = create_chanmon_cfgs(2);
6117         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6118         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6119         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6120
6121         let channel_value_satoshis=1000000;
6122         let push_msat=10001;
6123         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
6124         let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6125         node0_to_1_send_open_channel.dust_limit_satoshis = 547;
6126         node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
6127
6128         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
6129         let events = nodes[1].node.get_and_clear_pending_msg_events();
6130         let err_msg = match events[0] {
6131                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
6132                         msg.clone()
6133                 },
6134                 _ => panic!("Unexpected event"),
6135         };
6136         assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
6137 }
6138
6139 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
6140 // originated from our node, its failure is surfaced to the user. We trigger this failure to
6141 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
6142 // is no longer affordable once it's freed.
6143 #[test]
6144 fn test_fail_holding_cell_htlc_upon_free() {
6145         let chanmon_cfgs = create_chanmon_cfgs(2);
6146         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6147         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6148         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6149         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6150
6151         // First nodes[0] generates an update_fee, setting the channel's
6152         // pending_update_fee.
6153         {
6154                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6155                 *feerate_lock += 20;
6156         }
6157         nodes[0].node.timer_tick_occurred();
6158         check_added_monitors!(nodes[0], 1);
6159
6160         let events = nodes[0].node.get_and_clear_pending_msg_events();
6161         assert_eq!(events.len(), 1);
6162         let (update_msg, commitment_signed) = match events[0] {
6163                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6164                         (update_fee.as_ref(), commitment_signed)
6165                 },
6166                 _ => panic!("Unexpected event"),
6167         };
6168
6169         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6170
6171         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6172         let channel_reserve = chan_stat.channel_reserve_msat;
6173         let feerate = get_feerate!(nodes[0], chan.2);
6174         let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6175
6176         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6177         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6178         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6179
6180         // Send a payment which passes reserve checks but gets stuck in the holding cell.
6181         let our_payment_id = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6182         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6183         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6184
6185         // Flush the pending fee update.
6186         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6187         let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6188         check_added_monitors!(nodes[1], 1);
6189         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
6190         check_added_monitors!(nodes[0], 1);
6191
6192         // Upon receipt of the RAA, there will be an attempt to resend the holding cell
6193         // HTLC, but now that the fee has been raised the payment will now fail, causing
6194         // us to surface its failure to the user.
6195         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6196         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6197         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);
6198         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 {}",
6199                 hex::encode(our_payment_hash.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6200         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6201
6202         // Check that the payment failed to be sent out.
6203         let events = nodes[0].node.get_and_clear_pending_events();
6204         assert_eq!(events.len(), 1);
6205         match &events[0] {
6206                 &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, .. } => {
6207                         assert_eq!(our_payment_id, *payment_id.as_ref().unwrap());
6208                         assert_eq!(our_payment_hash.clone(), *payment_hash);
6209                         assert_eq!(*rejected_by_dest, false);
6210                         assert_eq!(*all_paths_failed, true);
6211                         assert_eq!(*network_update, None);
6212                         assert_eq!(*short_channel_id, None);
6213                         assert_eq!(*error_code, None);
6214                         assert_eq!(*error_data, None);
6215                 },
6216                 _ => panic!("Unexpected event"),
6217         }
6218 }
6219
6220 // Test that if multiple HTLCs are released from the holding cell and one is
6221 // valid but the other is no longer valid upon release, the valid HTLC can be
6222 // successfully completed while the other one fails as expected.
6223 #[test]
6224 fn test_free_and_fail_holding_cell_htlcs() {
6225         let chanmon_cfgs = create_chanmon_cfgs(2);
6226         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6227         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6228         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6229         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6230
6231         // First nodes[0] generates an update_fee, setting the channel's
6232         // pending_update_fee.
6233         {
6234                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6235                 *feerate_lock += 200;
6236         }
6237         nodes[0].node.timer_tick_occurred();
6238         check_added_monitors!(nodes[0], 1);
6239
6240         let events = nodes[0].node.get_and_clear_pending_msg_events();
6241         assert_eq!(events.len(), 1);
6242         let (update_msg, commitment_signed) = match events[0] {
6243                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6244                         (update_fee.as_ref(), commitment_signed)
6245                 },
6246                 _ => panic!("Unexpected event"),
6247         };
6248
6249         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6250
6251         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6252         let channel_reserve = chan_stat.channel_reserve_msat;
6253         let feerate = get_feerate!(nodes[0], chan.2);
6254         let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6255
6256         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6257         let amt_1 = 20000;
6258         let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors) - amt_1;
6259         let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
6260         let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
6261
6262         // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6263         nodes[0].node.send_payment(&route_1, payment_hash_1, &Some(payment_secret_1)).unwrap();
6264         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6265         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6266         let payment_id_2 = nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
6267         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6268         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6269
6270         // Flush the pending fee update.
6271         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6272         let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6273         check_added_monitors!(nodes[1], 1);
6274         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6275         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6276         check_added_monitors!(nodes[0], 2);
6277
6278         // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6279         // but now that the fee has been raised the second payment will now fail, causing us
6280         // to surface its failure to the user. The first payment should succeed.
6281         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6282         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6283         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);
6284         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 {}",
6285                 hex::encode(payment_hash_2.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6286         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6287
6288         // Check that the second payment failed to be sent out.
6289         let events = nodes[0].node.get_and_clear_pending_events();
6290         assert_eq!(events.len(), 1);
6291         match &events[0] {
6292                 &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, .. } => {
6293                         assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
6294                         assert_eq!(payment_hash_2.clone(), *payment_hash);
6295                         assert_eq!(*rejected_by_dest, false);
6296                         assert_eq!(*all_paths_failed, true);
6297                         assert_eq!(*network_update, None);
6298                         assert_eq!(*short_channel_id, None);
6299                         assert_eq!(*error_code, None);
6300                         assert_eq!(*error_data, None);
6301                 },
6302                 _ => panic!("Unexpected event"),
6303         }
6304
6305         // Complete the first payment and the RAA from the fee update.
6306         let (payment_event, send_raa_event) = {
6307                 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6308                 assert_eq!(msgs.len(), 2);
6309                 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6310         };
6311         let raa = match send_raa_event {
6312                 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6313                 _ => panic!("Unexpected event"),
6314         };
6315         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6316         check_added_monitors!(nodes[1], 1);
6317         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6318         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6319         let events = nodes[1].node.get_and_clear_pending_events();
6320         assert_eq!(events.len(), 1);
6321         match events[0] {
6322                 Event::PendingHTLCsForwardable { .. } => {},
6323                 _ => panic!("Unexpected event"),
6324         }
6325         nodes[1].node.process_pending_htlc_forwards();
6326         let events = nodes[1].node.get_and_clear_pending_events();
6327         assert_eq!(events.len(), 1);
6328         match events[0] {
6329                 Event::PaymentReceived { .. } => {},
6330                 _ => panic!("Unexpected event"),
6331         }
6332         nodes[1].node.claim_funds(payment_preimage_1);
6333         check_added_monitors!(nodes[1], 1);
6334         let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6335         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6336         commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6337         expect_payment_sent!(nodes[0], payment_preimage_1);
6338 }
6339
6340 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6341 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6342 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6343 // once it's freed.
6344 #[test]
6345 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6346         let chanmon_cfgs = create_chanmon_cfgs(3);
6347         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6348         // When this test was written, the default base fee floated based on the HTLC count.
6349         // It is now fixed, so we simply set the fee to the expected value here.
6350         let mut config = test_default_channel_config();
6351         config.channel_options.forwarding_fee_base_msat = 196;
6352         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
6353         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6354         let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6355         let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6356
6357         // First nodes[1] generates an update_fee, setting the channel's
6358         // pending_update_fee.
6359         {
6360                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
6361                 *feerate_lock += 20;
6362         }
6363         nodes[1].node.timer_tick_occurred();
6364         check_added_monitors!(nodes[1], 1);
6365
6366         let events = nodes[1].node.get_and_clear_pending_msg_events();
6367         assert_eq!(events.len(), 1);
6368         let (update_msg, commitment_signed) = match events[0] {
6369                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6370                         (update_fee.as_ref(), commitment_signed)
6371                 },
6372                 _ => panic!("Unexpected event"),
6373         };
6374
6375         nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6376
6377         let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
6378         let channel_reserve = chan_stat.channel_reserve_msat;
6379         let feerate = get_feerate!(nodes[0], chan_0_1.2);
6380         let opt_anchors = get_opt_anchors!(nodes[0], chan_0_1.2);
6381
6382         // Send a payment which passes reserve checks but gets stuck in the holding cell.
6383         let feemsat = 239;
6384         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
6385         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors) - total_routing_fee_msat;
6386         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
6387         let payment_event = {
6388                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6389                 check_added_monitors!(nodes[0], 1);
6390
6391                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6392                 assert_eq!(events.len(), 1);
6393
6394                 SendEvent::from_event(events.remove(0))
6395         };
6396         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6397         check_added_monitors!(nodes[1], 0);
6398         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6399         expect_pending_htlcs_forwardable!(nodes[1]);
6400
6401         chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
6402         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6403
6404         // Flush the pending fee update.
6405         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6406         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6407         check_added_monitors!(nodes[2], 1);
6408         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6409         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6410         check_added_monitors!(nodes[1], 2);
6411
6412         // A final RAA message is generated to finalize the fee update.
6413         let events = nodes[1].node.get_and_clear_pending_msg_events();
6414         assert_eq!(events.len(), 1);
6415
6416         let raa_msg = match &events[0] {
6417                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6418                         msg.clone()
6419                 },
6420                 _ => panic!("Unexpected event"),
6421         };
6422
6423         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6424         check_added_monitors!(nodes[2], 1);
6425         assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6426
6427         // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6428         let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6429         assert_eq!(process_htlc_forwards_event.len(), 1);
6430         match &process_htlc_forwards_event[0] {
6431                 &Event::PendingHTLCsForwardable { .. } => {},
6432                 _ => panic!("Unexpected event"),
6433         }
6434
6435         // In response, we call ChannelManager's process_pending_htlc_forwards
6436         nodes[1].node.process_pending_htlc_forwards();
6437         check_added_monitors!(nodes[1], 1);
6438
6439         // This causes the HTLC to be failed backwards.
6440         let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6441         assert_eq!(fail_event.len(), 1);
6442         let (fail_msg, commitment_signed) = match &fail_event[0] {
6443                 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6444                         assert_eq!(updates.update_add_htlcs.len(), 0);
6445                         assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6446                         assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6447                         assert_eq!(updates.update_fail_htlcs.len(), 1);
6448                         (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6449                 },
6450                 _ => panic!("Unexpected event"),
6451         };
6452
6453         // Pass the failure messages back to nodes[0].
6454         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6455         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6456
6457         // Complete the HTLC failure+removal process.
6458         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6459         check_added_monitors!(nodes[0], 1);
6460         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6461         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6462         check_added_monitors!(nodes[1], 2);
6463         let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6464         assert_eq!(final_raa_event.len(), 1);
6465         let raa = match &final_raa_event[0] {
6466                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6467                 _ => panic!("Unexpected event"),
6468         };
6469         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6470         expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6471         check_added_monitors!(nodes[0], 1);
6472 }
6473
6474 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6475 // 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.
6476 //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.
6477
6478 #[test]
6479 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6480         //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6481         let chanmon_cfgs = create_chanmon_cfgs(2);
6482         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6483         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6484         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6485         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6486
6487         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6488         route.paths[0][0].fee_msat = 100;
6489
6490         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6491                 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6492         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6493         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6494 }
6495
6496 #[test]
6497 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6498         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6499         let chanmon_cfgs = create_chanmon_cfgs(2);
6500         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6501         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6502         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6503         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6504
6505         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6506         route.paths[0][0].fee_msat = 0;
6507         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6508                 assert_eq!(err, "Cannot send 0-msat HTLC"));
6509
6510         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6511         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6512 }
6513
6514 #[test]
6515 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6516         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6517         let chanmon_cfgs = create_chanmon_cfgs(2);
6518         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6519         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6520         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6521         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6522
6523         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6524         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6525         check_added_monitors!(nodes[0], 1);
6526         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6527         updates.update_add_htlcs[0].amount_msat = 0;
6528
6529         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6530         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6531         check_closed_broadcast!(nodes[1], true).unwrap();
6532         check_added_monitors!(nodes[1], 1);
6533         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
6534 }
6535
6536 #[test]
6537 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6538         //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6539         //It is enforced when constructing a route.
6540         let chanmon_cfgs = create_chanmon_cfgs(2);
6541         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6542         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6543         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6544         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6545
6546         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
6547                 .with_features(InvoiceFeatures::known());
6548         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000, 0);
6549         route.paths[0].last_mut().unwrap().cltv_expiry_delta = 500000001;
6550         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::RouteError { ref err },
6551                 assert_eq!(err, &"Channel CLTV overflowed?"));
6552 }
6553
6554 #[test]
6555 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6556         //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.
6557         //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6558         //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6559         let chanmon_cfgs = create_chanmon_cfgs(2);
6560         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6561         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6562         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6563         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6564         let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6565
6566         for i in 0..max_accepted_htlcs {
6567                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6568                 let payment_event = {
6569                         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6570                         check_added_monitors!(nodes[0], 1);
6571
6572                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6573                         assert_eq!(events.len(), 1);
6574                         if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6575                                 assert_eq!(htlcs[0].htlc_id, i);
6576                         } else {
6577                                 assert!(false);
6578                         }
6579                         SendEvent::from_event(events.remove(0))
6580                 };
6581                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6582                 check_added_monitors!(nodes[1], 0);
6583                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6584
6585                 expect_pending_htlcs_forwardable!(nodes[1]);
6586                 expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6587         }
6588         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6589         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6590                 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6591
6592         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6593         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6594 }
6595
6596 #[test]
6597 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6598         //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.
6599         let chanmon_cfgs = create_chanmon_cfgs(2);
6600         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6601         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6602         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6603         let channel_value = 100000;
6604         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::known(), InitFeatures::known());
6605         let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6606
6607         send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6608
6609         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6610         // Manually create a route over our max in flight (which our router normally automatically
6611         // limits us to.
6612         route.paths[0][0].fee_msat =  max_in_flight + 1;
6613         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6614                 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)));
6615
6616         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6617         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);
6618
6619         send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6620 }
6621
6622 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6623 #[test]
6624 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6625         //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6626         let chanmon_cfgs = create_chanmon_cfgs(2);
6627         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6628         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6629         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6630         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6631         let htlc_minimum_msat: u64;
6632         {
6633                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6634                 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6635                 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6636         }
6637
6638         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6639         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6640         check_added_monitors!(nodes[0], 1);
6641         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6642         updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6643         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6644         assert!(nodes[1].node.list_channels().is_empty());
6645         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6646         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()));
6647         check_added_monitors!(nodes[1], 1);
6648         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6649 }
6650
6651 #[test]
6652 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6653         //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
6654         let chanmon_cfgs = create_chanmon_cfgs(2);
6655         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6656         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6657         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6658         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6659
6660         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6661         let channel_reserve = chan_stat.channel_reserve_msat;
6662         let feerate = get_feerate!(nodes[0], chan.2);
6663         let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6664         // The 2* and +1 are for the fee spike reserve.
6665         let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6666
6667         let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6668         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6669         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6670         check_added_monitors!(nodes[0], 1);
6671         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6672
6673         // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6674         // at this time channel-initiatee receivers are not required to enforce that senders
6675         // respect the fee_spike_reserve.
6676         updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6677         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6678
6679         assert!(nodes[1].node.list_channels().is_empty());
6680         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6681         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6682         check_added_monitors!(nodes[1], 1);
6683         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6684 }
6685
6686 #[test]
6687 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6688         //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6689         //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6690         let chanmon_cfgs = create_chanmon_cfgs(2);
6691         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6692         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6693         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6694         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6695
6696         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3999999);
6697         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6698         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6699         let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6700         let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &Some(our_payment_secret), cur_height, &None).unwrap();
6701         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6702
6703         let mut msg = msgs::UpdateAddHTLC {
6704                 channel_id: chan.2,
6705                 htlc_id: 0,
6706                 amount_msat: 1000,
6707                 payment_hash: our_payment_hash,
6708                 cltv_expiry: htlc_cltv,
6709                 onion_routing_packet: onion_packet.clone(),
6710         };
6711
6712         for i in 0..super::channel::OUR_MAX_HTLCS {
6713                 msg.htlc_id = i as u64;
6714                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6715         }
6716         msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6717         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6718
6719         assert!(nodes[1].node.list_channels().is_empty());
6720         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6721         assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6722         check_added_monitors!(nodes[1], 1);
6723         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6724 }
6725
6726 #[test]
6727 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6728         //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6729         let chanmon_cfgs = create_chanmon_cfgs(2);
6730         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6731         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6732         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6733         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6734
6735         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6736         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6737         check_added_monitors!(nodes[0], 1);
6738         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6739         updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6740         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6741
6742         assert!(nodes[1].node.list_channels().is_empty());
6743         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6744         assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6745         check_added_monitors!(nodes[1], 1);
6746         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6747 }
6748
6749 #[test]
6750 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6751         //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6752         let chanmon_cfgs = create_chanmon_cfgs(2);
6753         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6754         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6755         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6756
6757         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6758         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6759         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6760         check_added_monitors!(nodes[0], 1);
6761         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6762         updates.update_add_htlcs[0].cltv_expiry = 500000000;
6763         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6764
6765         assert!(nodes[1].node.list_channels().is_empty());
6766         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6767         assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6768         check_added_monitors!(nodes[1], 1);
6769         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6770 }
6771
6772 #[test]
6773 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6774         //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6775         // We test this by first testing that that repeated HTLCs pass commitment signature checks
6776         // after disconnect and that non-sequential htlc_ids result in a channel failure.
6777         let chanmon_cfgs = create_chanmon_cfgs(2);
6778         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6779         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6780         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6781
6782         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6783         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6784         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6785         check_added_monitors!(nodes[0], 1);
6786         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6787         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6788
6789         //Disconnect and Reconnect
6790         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6791         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6792         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
6793         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6794         assert_eq!(reestablish_1.len(), 1);
6795         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
6796         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6797         assert_eq!(reestablish_2.len(), 1);
6798         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6799         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6800         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6801         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6802
6803         //Resend HTLC
6804         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6805         assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6806         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6807         check_added_monitors!(nodes[1], 1);
6808         let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6809
6810         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6811
6812         assert!(nodes[1].node.list_channels().is_empty());
6813         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6814         assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6815         check_added_monitors!(nodes[1], 1);
6816         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6817 }
6818
6819 #[test]
6820 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6821         //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.
6822
6823         let chanmon_cfgs = create_chanmon_cfgs(2);
6824         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6825         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6826         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6827         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6828         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6829         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6830
6831         check_added_monitors!(nodes[0], 1);
6832         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6833         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6834
6835         let update_msg = msgs::UpdateFulfillHTLC{
6836                 channel_id: chan.2,
6837                 htlc_id: 0,
6838                 payment_preimage: our_payment_preimage,
6839         };
6840
6841         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6842
6843         assert!(nodes[0].node.list_channels().is_empty());
6844         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6845         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()));
6846         check_added_monitors!(nodes[0], 1);
6847         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6848 }
6849
6850 #[test]
6851 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6852         //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.
6853
6854         let chanmon_cfgs = create_chanmon_cfgs(2);
6855         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6856         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6857         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6858         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6859
6860         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6861         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6862         check_added_monitors!(nodes[0], 1);
6863         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6864         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6865
6866         let update_msg = msgs::UpdateFailHTLC{
6867                 channel_id: chan.2,
6868                 htlc_id: 0,
6869                 reason: msgs::OnionErrorPacket { data: Vec::new()},
6870         };
6871
6872         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6873
6874         assert!(nodes[0].node.list_channels().is_empty());
6875         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6876         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()));
6877         check_added_monitors!(nodes[0], 1);
6878         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6879 }
6880
6881 #[test]
6882 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6883         //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.
6884
6885         let chanmon_cfgs = create_chanmon_cfgs(2);
6886         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6887         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6888         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6889         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6890
6891         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6892         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6893         check_added_monitors!(nodes[0], 1);
6894         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6895         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6896         let update_msg = msgs::UpdateFailMalformedHTLC{
6897                 channel_id: chan.2,
6898                 htlc_id: 0,
6899                 sha256_of_onion: [1; 32],
6900                 failure_code: 0x8000,
6901         };
6902
6903         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6904
6905         assert!(nodes[0].node.list_channels().is_empty());
6906         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6907         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()));
6908         check_added_monitors!(nodes[0], 1);
6909         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6910 }
6911
6912 #[test]
6913 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6914         //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6915
6916         let chanmon_cfgs = create_chanmon_cfgs(2);
6917         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6918         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6919         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6920         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6921
6922         let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6923
6924         nodes[1].node.claim_funds(our_payment_preimage);
6925         check_added_monitors!(nodes[1], 1);
6926
6927         let events = nodes[1].node.get_and_clear_pending_msg_events();
6928         assert_eq!(events.len(), 1);
6929         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6930                 match events[0] {
6931                         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, .. } } => {
6932                                 assert!(update_add_htlcs.is_empty());
6933                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6934                                 assert!(update_fail_htlcs.is_empty());
6935                                 assert!(update_fail_malformed_htlcs.is_empty());
6936                                 assert!(update_fee.is_none());
6937                                 update_fulfill_htlcs[0].clone()
6938                         },
6939                         _ => panic!("Unexpected event"),
6940                 }
6941         };
6942
6943         update_fulfill_msg.htlc_id = 1;
6944
6945         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6946
6947         assert!(nodes[0].node.list_channels().is_empty());
6948         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6949         assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6950         check_added_monitors!(nodes[0], 1);
6951         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6952 }
6953
6954 #[test]
6955 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6956         //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.
6957
6958         let chanmon_cfgs = create_chanmon_cfgs(2);
6959         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6960         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6961         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6962         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6963
6964         let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6965
6966         nodes[1].node.claim_funds(our_payment_preimage);
6967         check_added_monitors!(nodes[1], 1);
6968
6969         let events = nodes[1].node.get_and_clear_pending_msg_events();
6970         assert_eq!(events.len(), 1);
6971         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6972                 match events[0] {
6973                         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, .. } } => {
6974                                 assert!(update_add_htlcs.is_empty());
6975                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6976                                 assert!(update_fail_htlcs.is_empty());
6977                                 assert!(update_fail_malformed_htlcs.is_empty());
6978                                 assert!(update_fee.is_none());
6979                                 update_fulfill_htlcs[0].clone()
6980                         },
6981                         _ => panic!("Unexpected event"),
6982                 }
6983         };
6984
6985         update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6986
6987         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6988
6989         assert!(nodes[0].node.list_channels().is_empty());
6990         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6991         assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6992         check_added_monitors!(nodes[0], 1);
6993         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6994 }
6995
6996 #[test]
6997 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6998         //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.
6999
7000         let chanmon_cfgs = create_chanmon_cfgs(2);
7001         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7002         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7003         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7004         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7005
7006         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
7007         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7008         check_added_monitors!(nodes[0], 1);
7009
7010         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7011         updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
7012
7013         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
7014         check_added_monitors!(nodes[1], 0);
7015         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
7016
7017         let events = nodes[1].node.get_and_clear_pending_msg_events();
7018
7019         let mut update_msg: msgs::UpdateFailMalformedHTLC = {
7020                 match events[0] {
7021                         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, .. } } => {
7022                                 assert!(update_add_htlcs.is_empty());
7023                                 assert!(update_fulfill_htlcs.is_empty());
7024                                 assert!(update_fail_htlcs.is_empty());
7025                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
7026                                 assert!(update_fee.is_none());
7027                                 update_fail_malformed_htlcs[0].clone()
7028                         },
7029                         _ => panic!("Unexpected event"),
7030                 }
7031         };
7032         update_msg.failure_code &= !0x8000;
7033         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
7034
7035         assert!(nodes[0].node.list_channels().is_empty());
7036         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
7037         assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
7038         check_added_monitors!(nodes[0], 1);
7039         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
7040 }
7041
7042 #[test]
7043 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
7044         //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
7045         //    * 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.
7046
7047         let chanmon_cfgs = create_chanmon_cfgs(3);
7048         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7049         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7050         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7051         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7052         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7053
7054         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
7055
7056         //First hop
7057         let mut payment_event = {
7058                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7059                 check_added_monitors!(nodes[0], 1);
7060                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7061                 assert_eq!(events.len(), 1);
7062                 SendEvent::from_event(events.remove(0))
7063         };
7064         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7065         check_added_monitors!(nodes[1], 0);
7066         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7067         expect_pending_htlcs_forwardable!(nodes[1]);
7068         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7069         assert_eq!(events_2.len(), 1);
7070         check_added_monitors!(nodes[1], 1);
7071         payment_event = SendEvent::from_event(events_2.remove(0));
7072         assert_eq!(payment_event.msgs.len(), 1);
7073
7074         //Second Hop
7075         payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
7076         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
7077         check_added_monitors!(nodes[2], 0);
7078         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
7079
7080         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
7081         assert_eq!(events_3.len(), 1);
7082         let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
7083                 match events_3[0] {
7084                         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 } } => {
7085                                 assert!(update_add_htlcs.is_empty());
7086                                 assert!(update_fulfill_htlcs.is_empty());
7087                                 assert!(update_fail_htlcs.is_empty());
7088                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
7089                                 assert!(update_fee.is_none());
7090                                 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
7091                         },
7092                         _ => panic!("Unexpected event"),
7093                 }
7094         };
7095
7096         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
7097
7098         check_added_monitors!(nodes[1], 0);
7099         commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
7100         expect_pending_htlcs_forwardable!(nodes[1]);
7101         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
7102         assert_eq!(events_4.len(), 1);
7103
7104         //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
7105         match events_4[0] {
7106                 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, .. } } => {
7107                         assert!(update_add_htlcs.is_empty());
7108                         assert!(update_fulfill_htlcs.is_empty());
7109                         assert_eq!(update_fail_htlcs.len(), 1);
7110                         assert!(update_fail_malformed_htlcs.is_empty());
7111                         assert!(update_fee.is_none());
7112                 },
7113                 _ => panic!("Unexpected event"),
7114         };
7115
7116         check_added_monitors!(nodes[1], 1);
7117 }
7118
7119 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
7120         // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
7121         // 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
7122         // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
7123
7124         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7125         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7126         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7127         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7128         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7129         let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7130
7131         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7132
7133         // We route 2 dust-HTLCs between A and B
7134         let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7135         let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7136         route_payment(&nodes[0], &[&nodes[1]], 1000000);
7137
7138         // Cache one local commitment tx as previous
7139         let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7140
7141         // Fail one HTLC to prune it in the will-be-latest-local commitment tx
7142         assert!(nodes[1].node.fail_htlc_backwards(&payment_hash_2));
7143         check_added_monitors!(nodes[1], 0);
7144         expect_pending_htlcs_forwardable!(nodes[1]);
7145         check_added_monitors!(nodes[1], 1);
7146
7147         let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7148         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
7149         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
7150         check_added_monitors!(nodes[0], 1);
7151
7152         // Cache one local commitment tx as lastest
7153         let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7154
7155         let events = nodes[0].node.get_and_clear_pending_msg_events();
7156         match events[0] {
7157                 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
7158                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7159                 },
7160                 _ => panic!("Unexpected event"),
7161         }
7162         match events[1] {
7163                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
7164                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7165                 },
7166                 _ => panic!("Unexpected event"),
7167         }
7168
7169         assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
7170         // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7171         if announce_latest {
7172                 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
7173         } else {
7174                 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
7175         }
7176
7177         check_closed_broadcast!(nodes[0], true);
7178         check_added_monitors!(nodes[0], 1);
7179         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7180
7181         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7182         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7183         let events = nodes[0].node.get_and_clear_pending_events();
7184         // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
7185         assert_eq!(events.len(), 2);
7186         let mut first_failed = false;
7187         for event in events {
7188                 match event {
7189                         Event::PaymentPathFailed { payment_hash, .. } => {
7190                                 if payment_hash == payment_hash_1 {
7191                                         assert!(!first_failed);
7192                                         first_failed = true;
7193                                 } else {
7194                                         assert_eq!(payment_hash, payment_hash_2);
7195                                 }
7196                         }
7197                         _ => panic!("Unexpected event"),
7198                 }
7199         }
7200 }
7201
7202 #[test]
7203 fn test_failure_delay_dust_htlc_local_commitment() {
7204         do_test_failure_delay_dust_htlc_local_commitment(true);
7205         do_test_failure_delay_dust_htlc_local_commitment(false);
7206 }
7207
7208 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7209         // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7210         // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7211         // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7212         // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7213         // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7214         // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7215
7216         let chanmon_cfgs = create_chanmon_cfgs(3);
7217         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7218         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7219         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7220         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7221
7222         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7223
7224         let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7225         let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7226
7227         let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7228         let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7229
7230         // We revoked bs_commitment_tx
7231         if revoked {
7232                 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7233                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
7234         }
7235
7236         let mut timeout_tx = Vec::new();
7237         if local {
7238                 // We fail dust-HTLC 1 by broadcast of local commitment tx
7239                 mine_transaction(&nodes[0], &as_commitment_tx[0]);
7240                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7241                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7242                 expect_payment_failed!(nodes[0], dust_hash, true);
7243
7244                 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
7245                 check_closed_broadcast!(nodes[0], true);
7246                 check_added_monitors!(nodes[0], 1);
7247                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7248                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
7249                 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7250                 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7251                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7252                 mine_transaction(&nodes[0], &timeout_tx[0]);
7253                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7254                 expect_payment_failed!(nodes[0], non_dust_hash, true);
7255         } else {
7256                 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7257                 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
7258                 check_closed_broadcast!(nodes[0], true);
7259                 check_added_monitors!(nodes[0], 1);
7260                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7261                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7262                 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7263                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
7264                 if !revoked {
7265                         expect_payment_failed!(nodes[0], dust_hash, true);
7266                         assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7267                         // We fail non-dust-HTLC 2 by broadcast of local timeout tx on remote commitment tx
7268                         mine_transaction(&nodes[0], &timeout_tx[0]);
7269                         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7270                         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7271                         expect_payment_failed!(nodes[0], non_dust_hash, true);
7272                 } else {
7273                         // If revoked, both dust & non-dust HTLCs should have been failed after ANTI_REORG_DELAY confs of revoked
7274                         // commitment tx
7275                         let events = nodes[0].node.get_and_clear_pending_events();
7276                         assert_eq!(events.len(), 2);
7277                         let first;
7278                         match events[0] {
7279                                 Event::PaymentPathFailed { payment_hash, .. } => {
7280                                         if payment_hash == dust_hash { first = true; }
7281                                         else { first = false; }
7282                                 },
7283                                 _ => panic!("Unexpected event"),
7284                         }
7285                         match events[1] {
7286                                 Event::PaymentPathFailed { payment_hash, .. } => {
7287                                         if first { assert_eq!(payment_hash, non_dust_hash); }
7288                                         else { assert_eq!(payment_hash, dust_hash); }
7289                                 },
7290                                 _ => panic!("Unexpected event"),
7291                         }
7292                 }
7293         }
7294 }
7295
7296 #[test]
7297 fn test_sweep_outbound_htlc_failure_update() {
7298         do_test_sweep_outbound_htlc_failure_update(false, true);
7299         do_test_sweep_outbound_htlc_failure_update(false, false);
7300         do_test_sweep_outbound_htlc_failure_update(true, false);
7301 }
7302
7303 #[test]
7304 fn test_user_configurable_csv_delay() {
7305         // We test our channel constructors yield errors when we pass them absurd csv delay
7306
7307         let mut low_our_to_self_config = UserConfig::default();
7308         low_our_to_self_config.own_channel_config.our_to_self_delay = 6;
7309         let mut high_their_to_self_config = UserConfig::default();
7310         high_their_to_self_config.peer_channel_config_limits.their_to_self_delay = 100;
7311         let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7312         let chanmon_cfgs = create_chanmon_cfgs(2);
7313         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7314         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7315         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7316
7317         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7318         if let Err(error) = Channel::new_outbound(&&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) },
7319                 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), 1000000, 1000000, 0,
7320                 &low_our_to_self_config, 0, 42)
7321         {
7322                 match error {
7323                         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())); },
7324                         _ => panic!("Unexpected event"),
7325                 }
7326         } else { assert!(false) }
7327
7328         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7329         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7330         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7331         open_channel.to_self_delay = 200;
7332         if let Err(error) = Channel::new_from_req(&&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) },
7333                 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), &open_channel, 0,
7334                 &low_our_to_self_config, 0, &nodes[0].logger, 42)
7335         {
7336                 match error {
7337                         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()));  },
7338                         _ => panic!("Unexpected event"),
7339                 }
7340         } else { assert!(false); }
7341
7342         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7343         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7344         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()));
7345         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7346         accept_channel.to_self_delay = 200;
7347         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7348         let reason_msg;
7349         if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7350                 match action {
7351                         &ErrorAction::SendErrorMessage { ref msg } => {
7352                                 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()));
7353                                 reason_msg = msg.data.clone();
7354                         },
7355                         _ => { panic!(); }
7356                 }
7357         } else { panic!(); }
7358         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg });
7359
7360         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7361         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7362         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7363         open_channel.to_self_delay = 200;
7364         if let Err(error) = Channel::new_from_req(&&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) },
7365                 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), &open_channel, 0,
7366                 &high_their_to_self_config, 0, &nodes[0].logger, 42)
7367         {
7368                 match error {
7369                         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())); },
7370                         _ => panic!("Unexpected event"),
7371                 }
7372         } else { assert!(false); }
7373 }
7374
7375 #[test]
7376 fn test_data_loss_protect() {
7377         // We want to be sure that :
7378         // * we don't broadcast our Local Commitment Tx in case of fallen behind
7379         //   (but this is not quite true - we broadcast during Drop because chanmon is out of sync with chanmgr)
7380         // * we close channel in case of detecting other being fallen behind
7381         // * we are able to claim our own outputs thanks to to_remote being static
7382         // TODO: this test is incomplete and the data_loss_protect implementation is incomplete - see issue #775
7383         let persister;
7384         let logger;
7385         let fee_estimator;
7386         let tx_broadcaster;
7387         let chain_source;
7388         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7389         // We broadcast during Drop because chanmon is out of sync with chanmgr, which would cause a panic
7390         // during signing due to revoked tx
7391         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7392         let keys_manager = &chanmon_cfgs[0].keys_manager;
7393         let monitor;
7394         let node_state_0;
7395         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7396         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7397         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7398
7399         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7400
7401         // Cache node A state before any channel update
7402         let previous_node_state = nodes[0].node.encode();
7403         let mut previous_chain_monitor_state = test_utils::TestVecWriter(Vec::new());
7404         get_monitor!(nodes[0], chan.2).write(&mut previous_chain_monitor_state).unwrap();
7405
7406         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7407         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7408
7409         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7410         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7411
7412         // Restore node A from previous state
7413         logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7414         let mut chain_monitor = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut io::Cursor::new(previous_chain_monitor_state.0), keys_manager).unwrap().1;
7415         chain_source = test_utils::TestChainSource::new(Network::Testnet);
7416         tx_broadcaster = test_utils::TestBroadcaster { txn_broadcasted: Mutex::new(Vec::new()), blocks: Arc::new(Mutex::new(Vec::new())) };
7417         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
7418         persister = test_utils::TestPersister::new();
7419         monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &tx_broadcaster, &logger, &fee_estimator, &persister, keys_manager);
7420         node_state_0 = {
7421                 let mut channel_monitors = HashMap::new();
7422                 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chain_monitor);
7423                 <(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 {
7424                         keys_manager: keys_manager,
7425                         fee_estimator: &fee_estimator,
7426                         chain_monitor: &monitor,
7427                         logger: &logger,
7428                         tx_broadcaster: &tx_broadcaster,
7429                         default_config: UserConfig::default(),
7430                         channel_monitors,
7431                 }).unwrap().1
7432         };
7433         nodes[0].node = &node_state_0;
7434         assert!(monitor.watch_channel(OutPoint { txid: chan.3.txid(), index: 0 }, chain_monitor).is_ok());
7435         nodes[0].chain_monitor = &monitor;
7436         nodes[0].chain_source = &chain_source;
7437
7438         check_added_monitors!(nodes[0], 1);
7439
7440         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7441         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7442
7443         let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7444
7445         // Check we don't broadcast any transactions following learning of per_commitment_point from B
7446         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7447         check_added_monitors!(nodes[0], 1);
7448
7449         {
7450                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7451                 assert_eq!(node_txn.len(), 0);
7452         }
7453
7454         let mut reestablish_1 = Vec::with_capacity(1);
7455         for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7456                 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
7457                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7458                         reestablish_1.push(msg.clone());
7459                 } else if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7460                 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7461                         match action {
7462                                 &ErrorAction::SendErrorMessage { ref msg } => {
7463                                         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");
7464                                 },
7465                                 _ => panic!("Unexpected event!"),
7466                         }
7467                 } else {
7468                         panic!("Unexpected event")
7469                 }
7470         }
7471
7472         // Check we close channel detecting A is fallen-behind
7473         // Check that we sent the warning message when we detected that A has fallen behind,
7474         // and give the possibility for A to recover from the warning.
7475         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7476         let warn_msg = "Peer attempted to reestablish channel with a very old local commitment transaction".to_owned();
7477         assert!(check_warn_msg!(nodes[1], nodes[0].node.get_our_node_id(), chan.2).contains(&warn_msg));
7478
7479         // Check A is able to claim to_remote output
7480         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7481         // The node B should not broadcast the transaction to force close the channel!
7482         assert!(node_txn.is_empty());
7483         // B should now detect that there is something wrong and should force close the channel.
7484         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";
7485         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: exp_err.to_string() });
7486
7487         // after the warning message sent by B, we should not able to
7488         // use the channel, or reconnect with success to the channel.
7489         assert!(nodes[0].node.list_usable_channels().is_empty());
7490         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7491         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7492         let retry_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7493
7494         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &retry_reestablish[0]);
7495         let mut err_msgs_0 = Vec::with_capacity(1);
7496         for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7497                 if let MessageSendEvent::HandleError { ref action, .. } = msg {
7498                         match action {
7499                                 &ErrorAction::SendErrorMessage { ref msg } => {
7500                                         assert_eq!(msg.data, "Failed to find corresponding channel");
7501                                         err_msgs_0.push(msg.clone());
7502                                 },
7503                                 _ => panic!("Unexpected event!"),
7504                         }
7505                 } else {
7506                         panic!("Unexpected event!");
7507                 }
7508         }
7509         assert_eq!(err_msgs_0.len(), 1);
7510         nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), &err_msgs_0[0]);
7511         assert!(nodes[1].node.list_usable_channels().is_empty());
7512         check_added_monitors!(nodes[1], 1);
7513         check_closed_event!(nodes[1], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "Failed to find corresponding channel".to_owned() });
7514         check_closed_broadcast!(nodes[1], false);
7515 }
7516
7517 #[test]
7518 fn test_check_htlc_underpaying() {
7519         // Send payment through A -> B but A is maliciously
7520         // sending a probe payment (i.e less than expected value0
7521         // to B, B should refuse payment.
7522
7523         let chanmon_cfgs = create_chanmon_cfgs(2);
7524         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7525         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7526         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7527
7528         // Create some initial channels
7529         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7530
7531         let scorer = test_utils::TestScorer::with_penalty(0);
7532         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7533         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7534         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();
7535         let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7536         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200).unwrap();
7537         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7538         check_added_monitors!(nodes[0], 1);
7539
7540         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7541         assert_eq!(events.len(), 1);
7542         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7543         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7544         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7545
7546         // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7547         // and then will wait a second random delay before failing the HTLC back:
7548         expect_pending_htlcs_forwardable!(nodes[1]);
7549         expect_pending_htlcs_forwardable!(nodes[1]);
7550
7551         // Node 3 is expecting payment of 100_000 but received 10_000,
7552         // it should fail htlc like we didn't know the preimage.
7553         nodes[1].node.process_pending_htlc_forwards();
7554
7555         let events = nodes[1].node.get_and_clear_pending_msg_events();
7556         assert_eq!(events.len(), 1);
7557         let (update_fail_htlc, commitment_signed) = match events[0] {
7558                 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 } } => {
7559                         assert!(update_add_htlcs.is_empty());
7560                         assert!(update_fulfill_htlcs.is_empty());
7561                         assert_eq!(update_fail_htlcs.len(), 1);
7562                         assert!(update_fail_malformed_htlcs.is_empty());
7563                         assert!(update_fee.is_none());
7564                         (update_fail_htlcs[0].clone(), commitment_signed)
7565                 },
7566                 _ => panic!("Unexpected event"),
7567         };
7568         check_added_monitors!(nodes[1], 1);
7569
7570         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7571         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7572
7573         // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7574         let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7575         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(CHAN_CONFIRM_DEPTH));
7576         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7577 }
7578
7579 #[test]
7580 fn test_announce_disable_channels() {
7581         // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7582         // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7583
7584         let chanmon_cfgs = create_chanmon_cfgs(2);
7585         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7586         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7587         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7588
7589         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7590         create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::known(), InitFeatures::known());
7591         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7592
7593         // Disconnect peers
7594         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7595         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7596
7597         nodes[0].node.timer_tick_occurred(); // Enabled -> DisabledStaged
7598         nodes[0].node.timer_tick_occurred(); // DisabledStaged -> Disabled
7599         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7600         assert_eq!(msg_events.len(), 3);
7601         let mut chans_disabled = HashMap::new();
7602         for e in msg_events {
7603                 match e {
7604                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7605                                 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7606                                 // Check that each channel gets updated exactly once
7607                                 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7608                                         panic!("Generated ChannelUpdate for wrong chan!");
7609                                 }
7610                         },
7611                         _ => panic!("Unexpected event"),
7612                 }
7613         }
7614         // Reconnect peers
7615         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7616         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7617         assert_eq!(reestablish_1.len(), 3);
7618         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7619         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7620         assert_eq!(reestablish_2.len(), 3);
7621
7622         // Reestablish chan_1
7623         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7624         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7625         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7626         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7627         // Reestablish chan_2
7628         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7629         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7630         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7631         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7632         // Reestablish chan_3
7633         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7634         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7635         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7636         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7637
7638         nodes[0].node.timer_tick_occurred();
7639         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7640         nodes[0].node.timer_tick_occurred();
7641         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7642         assert_eq!(msg_events.len(), 3);
7643         for e in msg_events {
7644                 match e {
7645                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7646                                 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7647                                 match chans_disabled.remove(&msg.contents.short_channel_id) {
7648                                         // Each update should have a higher timestamp than the previous one, replacing
7649                                         // the old one.
7650                                         Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7651                                         None => panic!("Generated ChannelUpdate for wrong chan!"),
7652                                 }
7653                         },
7654                         _ => panic!("Unexpected event"),
7655                 }
7656         }
7657         // Check that each channel gets updated exactly once
7658         assert!(chans_disabled.is_empty());
7659 }
7660
7661 #[test]
7662 fn test_bump_penalty_txn_on_revoked_commitment() {
7663         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7664         // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7665
7666         let chanmon_cfgs = create_chanmon_cfgs(2);
7667         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7668         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7669         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7670
7671         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7672
7673         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7674         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id())
7675                 .with_features(InvoiceFeatures::known());
7676         let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000, 30);
7677         send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7678
7679         let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7680         // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7681         assert_eq!(revoked_txn[0].output.len(), 4);
7682         assert_eq!(revoked_txn[0].input.len(), 1);
7683         assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7684         let revoked_txid = revoked_txn[0].txid();
7685
7686         let mut penalty_sum = 0;
7687         for outp in revoked_txn[0].output.iter() {
7688                 if outp.script_pubkey.is_v0_p2wsh() {
7689                         penalty_sum += outp.value;
7690                 }
7691         }
7692
7693         // Connect blocks to change height_timer range to see if we use right soonest_timelock
7694         let header_114 = connect_blocks(&nodes[1], 14);
7695
7696         // Actually revoke tx by claiming a HTLC
7697         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7698         let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7699         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] });
7700         check_added_monitors!(nodes[1], 1);
7701
7702         // One or more justice tx should have been broadcast, check it
7703         let penalty_1;
7704         let feerate_1;
7705         {
7706                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7707                 assert_eq!(node_txn.len(), 2); // justice tx (broadcasted from ChannelMonitor) + local commitment tx
7708                 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7709                 assert_eq!(node_txn[0].output.len(), 1);
7710                 check_spends!(node_txn[0], revoked_txn[0]);
7711                 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7712                 feerate_1 = fee_1 * 1000 / node_txn[0].weight() as u64;
7713                 penalty_1 = node_txn[0].txid();
7714                 node_txn.clear();
7715         };
7716
7717         // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7718         connect_blocks(&nodes[1], 15);
7719         let mut penalty_2 = penalty_1;
7720         let mut feerate_2 = 0;
7721         {
7722                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7723                 assert_eq!(node_txn.len(), 1);
7724                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7725                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7726                         assert_eq!(node_txn[0].output.len(), 1);
7727                         check_spends!(node_txn[0], revoked_txn[0]);
7728                         penalty_2 = node_txn[0].txid();
7729                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7730                         assert_ne!(penalty_2, penalty_1);
7731                         let fee_2 = penalty_sum - node_txn[0].output[0].value;
7732                         feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7733                         // Verify 25% bump heuristic
7734                         assert!(feerate_2 * 100 >= feerate_1 * 125);
7735                         node_txn.clear();
7736                 }
7737         }
7738         assert_ne!(feerate_2, 0);
7739
7740         // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7741         connect_blocks(&nodes[1], 1);
7742         let penalty_3;
7743         let mut feerate_3 = 0;
7744         {
7745                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7746                 assert_eq!(node_txn.len(), 1);
7747                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7748                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7749                         assert_eq!(node_txn[0].output.len(), 1);
7750                         check_spends!(node_txn[0], revoked_txn[0]);
7751                         penalty_3 = node_txn[0].txid();
7752                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7753                         assert_ne!(penalty_3, penalty_2);
7754                         let fee_3 = penalty_sum - node_txn[0].output[0].value;
7755                         feerate_3 = fee_3 * 1000 / node_txn[0].weight() as u64;
7756                         // Verify 25% bump heuristic
7757                         assert!(feerate_3 * 100 >= feerate_2 * 125);
7758                         node_txn.clear();
7759                 }
7760         }
7761         assert_ne!(feerate_3, 0);
7762
7763         nodes[1].node.get_and_clear_pending_events();
7764         nodes[1].node.get_and_clear_pending_msg_events();
7765 }
7766
7767 #[test]
7768 fn test_bump_penalty_txn_on_revoked_htlcs() {
7769         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7770         // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7771
7772         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7773         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7774         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7775         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7776         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7777
7778         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7779         // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7780         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7781         let scorer = test_utils::TestScorer::with_penalty(0);
7782         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7783         let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None,
7784                 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7785         let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7786         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7787         let route = get_route(&nodes[1].node.get_our_node_id(), &payment_params, &nodes[1].network_graph.read_only(), None,
7788                 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7789         send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7790
7791         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7792         assert_eq!(revoked_local_txn[0].input.len(), 1);
7793         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7794
7795         // Revoke local commitment tx
7796         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7797
7798         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7799         // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7800         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] });
7801         check_closed_broadcast!(nodes[1], true);
7802         check_added_monitors!(nodes[1], 1);
7803         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7804         connect_blocks(&nodes[1], 49); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7805
7806         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7807         assert_eq!(revoked_htlc_txn.len(), 3);
7808         check_spends!(revoked_htlc_txn[1], chan.3);
7809
7810         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7811         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7812         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7813
7814         assert_eq!(revoked_htlc_txn[2].input.len(), 1);
7815         assert_eq!(revoked_htlc_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7816         assert_eq!(revoked_htlc_txn[2].output.len(), 1);
7817         check_spends!(revoked_htlc_txn[2], revoked_local_txn[0]);
7818
7819         // Broadcast set of revoked txn on A
7820         let hash_128 = connect_blocks(&nodes[0], 40);
7821         let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7822         connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] });
7823         let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7824         connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[2].clone()] });
7825         let events = nodes[0].node.get_and_clear_pending_events();
7826         expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7827         match events[1] {
7828                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7829                 _ => panic!("Unexpected event"),
7830         }
7831         let first;
7832         let feerate_1;
7833         let penalty_txn;
7834         {
7835                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7836                 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7837                 // Verify claim tx are spending revoked HTLC txn
7838
7839                 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7840                 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7841                 // which are included in the same block (they are broadcasted because we scan the
7842                 // transactions linearly and generate claims as we go, they likely should be removed in the
7843                 // future).
7844                 assert_eq!(node_txn[0].input.len(), 1);
7845                 check_spends!(node_txn[0], revoked_local_txn[0]);
7846                 assert_eq!(node_txn[1].input.len(), 1);
7847                 check_spends!(node_txn[1], revoked_local_txn[0]);
7848                 assert_eq!(node_txn[2].input.len(), 1);
7849                 check_spends!(node_txn[2], revoked_local_txn[0]);
7850
7851                 // Each of the three justice transactions claim a separate (single) output of the three
7852                 // available, which we check here:
7853                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7854                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7855                 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7856
7857                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7858                 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7859
7860                 // node_txn[3] is the local commitment tx broadcast just because (and somewhat in case of
7861                 // reorgs, though its not clear its ever worth broadcasting conflicting txn like this when
7862                 // a remote commitment tx has already been confirmed).
7863                 check_spends!(node_txn[3], chan.3);
7864
7865                 // node_txn[4] spends the revoked outputs from the revoked_htlc_txn (which only have one
7866                 // output, checked above).
7867                 assert_eq!(node_txn[4].input.len(), 2);
7868                 assert_eq!(node_txn[4].output.len(), 1);
7869                 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7870
7871                 first = node_txn[4].txid();
7872                 // Store both feerates for later comparison
7873                 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[4].output[0].value;
7874                 feerate_1 = fee_1 * 1000 / node_txn[4].weight() as u64;
7875                 penalty_txn = vec![node_txn[2].clone()];
7876                 node_txn.clear();
7877         }
7878
7879         // Connect one more block to see if bumped penalty are issued for HTLC txn
7880         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7881         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7882         let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7883         connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() });
7884         {
7885                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7886                 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7887
7888                 check_spends!(node_txn[0], revoked_local_txn[0]);
7889                 check_spends!(node_txn[1], revoked_local_txn[0]);
7890                 // Note that these are both bogus - they spend outputs already claimed in block 129:
7891                 if node_txn[0].input[0].previous_output == revoked_htlc_txn[0].input[0].previous_output  {
7892                         assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7893                 } else {
7894                         assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7895                         assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7896                 }
7897
7898                 node_txn.clear();
7899         };
7900
7901         // Few more blocks to confirm penalty txn
7902         connect_blocks(&nodes[0], 4);
7903         assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7904         let header_144 = connect_blocks(&nodes[0], 9);
7905         let node_txn = {
7906                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7907                 assert_eq!(node_txn.len(), 1);
7908
7909                 assert_eq!(node_txn[0].input.len(), 2);
7910                 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7911                 // Verify bumped tx is different and 25% bump heuristic
7912                 assert_ne!(first, node_txn[0].txid());
7913                 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[0].output[0].value;
7914                 let feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7915                 assert!(feerate_2 * 100 > feerate_1 * 125);
7916                 let txn = vec![node_txn[0].clone()];
7917                 node_txn.clear();
7918                 txn
7919         };
7920         // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7921         let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7922         connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn });
7923         connect_blocks(&nodes[0], 20);
7924         {
7925                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7926                 // We verify than no new transaction has been broadcast because previously
7927                 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7928                 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7929                 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7930                 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7931                 // up bumped justice generation.
7932                 assert_eq!(node_txn.len(), 0);
7933                 node_txn.clear();
7934         }
7935         check_closed_broadcast!(nodes[0], true);
7936         check_added_monitors!(nodes[0], 1);
7937 }
7938
7939 #[test]
7940 fn test_bump_penalty_txn_on_remote_commitment() {
7941         // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7942         // we're able to claim outputs on remote commitment transaction before timelocks expiration
7943
7944         // Create 2 HTLCs
7945         // Provide preimage for one
7946         // Check aggregation
7947
7948         let chanmon_cfgs = create_chanmon_cfgs(2);
7949         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7950         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7951         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7952
7953         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7954         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7955         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7956
7957         // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7958         let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7959         assert_eq!(remote_txn[0].output.len(), 4);
7960         assert_eq!(remote_txn[0].input.len(), 1);
7961         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7962
7963         // Claim a HTLC without revocation (provide B monitor with preimage)
7964         nodes[1].node.claim_funds(payment_preimage);
7965         mine_transaction(&nodes[1], &remote_txn[0]);
7966         check_added_monitors!(nodes[1], 2);
7967         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7968
7969         // One or more claim tx should have been broadcast, check it
7970         let timeout;
7971         let preimage;
7972         let preimage_bump;
7973         let feerate_timeout;
7974         let feerate_preimage;
7975         {
7976                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7977                 // 9 transactions including:
7978                 // 1*2 ChannelManager local broadcasts of commitment + HTLC-Success
7979                 // 1*3 ChannelManager local broadcasts of commitment + HTLC-Success + HTLC-Timeout
7980                 // 2 * HTLC-Success (one RBF bump we'll check later)
7981                 // 1 * HTLC-Timeout
7982                 assert_eq!(node_txn.len(), 8);
7983                 assert_eq!(node_txn[0].input.len(), 1);
7984                 assert_eq!(node_txn[6].input.len(), 1);
7985                 check_spends!(node_txn[0], remote_txn[0]);
7986                 check_spends!(node_txn[6], remote_txn[0]);
7987
7988                 check_spends!(node_txn[1], chan.3);
7989                 check_spends!(node_txn[2], node_txn[1]);
7990
7991                 if node_txn[0].input[0].previous_output == node_txn[3].input[0].previous_output {
7992                         preimage_bump = node_txn[3].clone();
7993                         check_spends!(node_txn[3], remote_txn[0]);
7994
7995                         assert_eq!(node_txn[1], node_txn[4]);
7996                         assert_eq!(node_txn[2], node_txn[5]);
7997                 } else {
7998                         preimage_bump = node_txn[7].clone();
7999                         check_spends!(node_txn[7], remote_txn[0]);
8000                         assert_eq!(node_txn[0].input[0].previous_output, node_txn[7].input[0].previous_output);
8001
8002                         assert_eq!(node_txn[1], node_txn[3]);
8003                         assert_eq!(node_txn[2], node_txn[4]);
8004                 }
8005
8006                 timeout = node_txn[6].txid();
8007                 let index = node_txn[6].input[0].previous_output.vout;
8008                 let fee = remote_txn[0].output[index as usize].value - node_txn[6].output[0].value;
8009                 feerate_timeout = fee * 1000 / node_txn[6].weight() as u64;
8010
8011                 preimage = node_txn[0].txid();
8012                 let index = node_txn[0].input[0].previous_output.vout;
8013                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8014                 feerate_preimage = fee * 1000 / node_txn[0].weight() as u64;
8015
8016                 node_txn.clear();
8017         };
8018         assert_ne!(feerate_timeout, 0);
8019         assert_ne!(feerate_preimage, 0);
8020
8021         // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
8022         connect_blocks(&nodes[1], 15);
8023         {
8024                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8025                 assert_eq!(node_txn.len(), 1);
8026                 assert_eq!(node_txn[0].input.len(), 1);
8027                 assert_eq!(preimage_bump.input.len(), 1);
8028                 check_spends!(node_txn[0], remote_txn[0]);
8029                 check_spends!(preimage_bump, remote_txn[0]);
8030
8031                 let index = preimage_bump.input[0].previous_output.vout;
8032                 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
8033                 let new_feerate = fee * 1000 / preimage_bump.weight() as u64;
8034                 assert!(new_feerate * 100 > feerate_timeout * 125);
8035                 assert_ne!(timeout, preimage_bump.txid());
8036
8037                 let index = node_txn[0].input[0].previous_output.vout;
8038                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8039                 let new_feerate = fee * 1000 / node_txn[0].weight() as u64;
8040                 assert!(new_feerate * 100 > feerate_preimage * 125);
8041                 assert_ne!(preimage, node_txn[0].txid());
8042
8043                 node_txn.clear();
8044         }
8045
8046         nodes[1].node.get_and_clear_pending_events();
8047         nodes[1].node.get_and_clear_pending_msg_events();
8048 }
8049
8050 #[test]
8051 fn test_counterparty_raa_skip_no_crash() {
8052         // Previously, if our counterparty sent two RAAs in a row without us having provided a
8053         // commitment transaction, we would have happily carried on and provided them the next
8054         // commitment transaction based on one RAA forward. This would probably eventually have led to
8055         // channel closure, but it would not have resulted in funds loss. Still, our
8056         // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
8057         // check simply that the channel is closed in response to such an RAA, but don't check whether
8058         // we decide to punish our counterparty for revoking their funds (as we don't currently
8059         // implement that).
8060         let chanmon_cfgs = create_chanmon_cfgs(2);
8061         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8062         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8063         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8064         let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
8065
8066         let mut guard = nodes[0].node.channel_state.lock().unwrap();
8067         let keys = guard.by_id.get_mut(&channel_id).unwrap().get_signer();
8068
8069         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
8070
8071         // Make signer believe we got a counterparty signature, so that it allows the revocation
8072         keys.get_enforcement_state().last_holder_commitment -= 1;
8073         let per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
8074
8075         // Must revoke without gaps
8076         keys.get_enforcement_state().last_holder_commitment -= 1;
8077         keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
8078
8079         keys.get_enforcement_state().last_holder_commitment -= 1;
8080         let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
8081                 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
8082
8083         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
8084                 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
8085         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
8086         check_added_monitors!(nodes[1], 1);
8087         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
8088 }
8089
8090 #[test]
8091 fn test_bump_txn_sanitize_tracking_maps() {
8092         // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
8093         // verify we clean then right after expiration of ANTI_REORG_DELAY.
8094
8095         let chanmon_cfgs = create_chanmon_cfgs(2);
8096         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8097         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8098         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8099
8100         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8101         // Lock HTLC in both directions
8102         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8103         route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
8104
8105         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
8106         assert_eq!(revoked_local_txn[0].input.len(), 1);
8107         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8108
8109         // Revoke local commitment tx
8110         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
8111
8112         // Broadcast set of revoked txn on A
8113         connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
8114         expect_pending_htlcs_forwardable_ignore!(nodes[0]);
8115         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
8116
8117         mine_transaction(&nodes[0], &revoked_local_txn[0]);
8118         check_closed_broadcast!(nodes[0], true);
8119         check_added_monitors!(nodes[0], 1);
8120         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8121         let penalty_txn = {
8122                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8123                 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
8124                 check_spends!(node_txn[0], revoked_local_txn[0]);
8125                 check_spends!(node_txn[1], revoked_local_txn[0]);
8126                 check_spends!(node_txn[2], revoked_local_txn[0]);
8127                 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
8128                 node_txn.clear();
8129                 penalty_txn
8130         };
8131         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8132         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
8133         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8134         {
8135                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
8136                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
8137                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
8138         }
8139 }
8140
8141 #[test]
8142 fn test_pending_claimed_htlc_no_balance_underflow() {
8143         // Tests that if we have a pending outbound HTLC as well as a claimed-but-not-fully-removed
8144         // HTLC we will not underflow when we call `Channel::get_balance_msat()`.
8145         let chanmon_cfgs = create_chanmon_cfgs(2);
8146         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8147         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8148         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8149         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
8150
8151         let payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 1_010_000).0;
8152         nodes[1].node.claim_funds(payment_preimage);
8153         check_added_monitors!(nodes[1], 1);
8154         let fulfill_ev = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8155
8156         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &fulfill_ev.update_fulfill_htlcs[0]);
8157         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
8158         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &fulfill_ev.commitment_signed);
8159         check_added_monitors!(nodes[0], 1);
8160         let (_raa, _cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
8161
8162         // At this point nodes[1] has received 1,010k msat (10k msat more than their reserve) and can
8163         // send an HTLC back (though it will go in the holding cell). Send an HTLC back and check we
8164         // can get our balance.
8165
8166         // Get a route from nodes[1] to nodes[0] by getting a route going the other way and then flip
8167         // the public key of the only hop. This works around ChannelDetails not showing the
8168         // almost-claimed HTLC as available balance.
8169         let (mut route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 10_000);
8170         route.payment_params = None; // This is all wrong, but unnecessary
8171         route.paths[0][0].pubkey = nodes[0].node.get_our_node_id();
8172         let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[0]);
8173         nodes[1].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
8174
8175         assert_eq!(nodes[1].node.list_channels()[0].balance_msat, 1_000_000);
8176 }
8177
8178 #[test]
8179 fn test_channel_conf_timeout() {
8180         // Tests that, for inbound channels, we give up on them if the funding transaction does not
8181         // confirm within 2016 blocks, as recommended by BOLT 2.
8182         let chanmon_cfgs = create_chanmon_cfgs(2);
8183         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8184         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8185         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8186
8187         let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000, InitFeatures::known(), InitFeatures::known());
8188
8189         // The outbound node should wait forever for confirmation:
8190         // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
8191         // copied here instead of directly referencing the constant.
8192         connect_blocks(&nodes[0], 2016);
8193         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8194
8195         // The inbound node should fail the channel after exactly 2016 blocks
8196         connect_blocks(&nodes[1], 2015);
8197         check_added_monitors!(nodes[1], 0);
8198         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8199
8200         connect_blocks(&nodes[1], 1);
8201         check_added_monitors!(nodes[1], 1);
8202         check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut);
8203         let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
8204         assert_eq!(close_ev.len(), 1);
8205         match close_ev[0] {
8206                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
8207                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8208                         assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
8209                 },
8210                 _ => panic!("Unexpected event"),
8211         }
8212 }
8213
8214 #[test]
8215 fn test_override_channel_config() {
8216         let chanmon_cfgs = create_chanmon_cfgs(2);
8217         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8218         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8219         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8220
8221         // Node0 initiates a channel to node1 using the override config.
8222         let mut override_config = UserConfig::default();
8223         override_config.own_channel_config.our_to_self_delay = 200;
8224
8225         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
8226
8227         // Assert the channel created by node0 is using the override config.
8228         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8229         assert_eq!(res.channel_flags, 0);
8230         assert_eq!(res.to_self_delay, 200);
8231 }
8232
8233 #[test]
8234 fn test_override_0msat_htlc_minimum() {
8235         let mut zero_config = UserConfig::default();
8236         zero_config.own_channel_config.our_htlc_minimum_msat = 0;
8237         let chanmon_cfgs = create_chanmon_cfgs(2);
8238         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8239         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
8240         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8241
8242         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
8243         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8244         assert_eq!(res.htlc_minimum_msat, 1);
8245
8246         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8247         let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8248         assert_eq!(res.htlc_minimum_msat, 1);
8249 }
8250
8251 #[test]
8252 fn test_channel_update_has_correct_htlc_maximum_msat() {
8253         // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
8254         // Bolt 7 specifies that if present `htlc_maximum_msat`:
8255         // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
8256         // 90% of the `channel_value`.
8257         // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
8258
8259         let mut config_30_percent = UserConfig::default();
8260         config_30_percent.channel_options.announced_channel = true;
8261         config_30_percent.own_channel_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
8262         let mut config_50_percent = UserConfig::default();
8263         config_50_percent.channel_options.announced_channel = true;
8264         config_50_percent.own_channel_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
8265         let mut config_95_percent = UserConfig::default();
8266         config_95_percent.channel_options.announced_channel = true;
8267         config_95_percent.own_channel_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
8268         let mut config_100_percent = UserConfig::default();
8269         config_100_percent.channel_options.announced_channel = true;
8270         config_100_percent.own_channel_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
8271
8272         let chanmon_cfgs = create_chanmon_cfgs(4);
8273         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8274         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)]);
8275         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8276
8277         let channel_value_satoshis = 100000;
8278         let channel_value_msat = channel_value_satoshis * 1000;
8279         let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
8280         let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
8281         let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
8282
8283         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());
8284         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());
8285
8286         // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
8287         // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
8288         assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, OptionalField::Present(channel_value_50_percent_msat));
8289         // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
8290         // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
8291         assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, OptionalField::Present(channel_value_30_percent_msat));
8292
8293         // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
8294         // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
8295         // `channel_value`.
8296         assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, OptionalField::Present(channel_value_90_percent_msat));
8297         // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
8298         // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
8299         // `channel_value`.
8300         assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, OptionalField::Present(channel_value_90_percent_msat));
8301 }
8302
8303 #[test]
8304 fn test_manually_accept_inbound_channel_request() {
8305         let mut manually_accept_conf = UserConfig::default();
8306         manually_accept_conf.manually_accept_inbound_channels = true;
8307         let chanmon_cfgs = create_chanmon_cfgs(2);
8308         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8309         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8310         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8311
8312         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8313         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8314
8315         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8316
8317         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8318         // accepting the inbound channel request.
8319         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8320
8321         let events = nodes[1].node.get_and_clear_pending_events();
8322         match events[0] {
8323                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8324                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
8325                 }
8326                 _ => panic!("Unexpected event"),
8327         }
8328
8329         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8330         assert_eq!(accept_msg_ev.len(), 1);
8331
8332         match accept_msg_ev[0] {
8333                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8334                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8335                 }
8336                 _ => panic!("Unexpected event"),
8337         }
8338
8339         nodes[1].node.force_close_channel(&temp_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
8340
8341         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8342         assert_eq!(close_msg_ev.len(), 1);
8343
8344         let events = nodes[1].node.get_and_clear_pending_events();
8345         match events[0] {
8346                 Event::ChannelClosed { user_channel_id, .. } => {
8347                         assert_eq!(user_channel_id, 23);
8348                 }
8349                 _ => panic!("Unexpected event"),
8350         }
8351 }
8352
8353 #[test]
8354 fn test_manually_reject_inbound_channel_request() {
8355         let mut manually_accept_conf = UserConfig::default();
8356         manually_accept_conf.manually_accept_inbound_channels = true;
8357         let chanmon_cfgs = create_chanmon_cfgs(2);
8358         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8359         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8360         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8361
8362         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8363         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8364
8365         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8366
8367         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8368         // rejecting the inbound channel request.
8369         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8370
8371         let events = nodes[1].node.get_and_clear_pending_events();
8372         match events[0] {
8373                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8374                         nodes[1].node.force_close_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
8375                 }
8376                 _ => panic!("Unexpected event"),
8377         }
8378
8379         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8380         assert_eq!(close_msg_ev.len(), 1);
8381
8382         match close_msg_ev[0] {
8383                 MessageSendEvent::HandleError { ref node_id, .. } => {
8384                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8385                 }
8386                 _ => panic!("Unexpected event"),
8387         }
8388         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
8389 }
8390
8391 #[test]
8392 fn test_reject_funding_before_inbound_channel_accepted() {
8393         // This tests that when `UserConfig::manually_accept_inbound_channels` is set to true, inbound
8394         // channels must to be manually accepted through `ChannelManager::accept_inbound_channel` by
8395         // the node operator before the counterparty sends a `FundingCreated` message. If a
8396         // `FundingCreated` message is received before the channel is accepted, it should be rejected
8397         // and the channel should be closed.
8398         let mut manually_accept_conf = UserConfig::default();
8399         manually_accept_conf.manually_accept_inbound_channels = true;
8400         let chanmon_cfgs = create_chanmon_cfgs(2);
8401         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8402         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8403         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8404
8405         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8406         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8407         let temp_channel_id = res.temporary_channel_id;
8408
8409         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8410
8411         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in the `msg_events`.
8412         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8413
8414         // Clear the `Event::OpenChannelRequest` event without responding to the request.
8415         nodes[1].node.get_and_clear_pending_events();
8416
8417         // Get the `AcceptChannel` message of `nodes[1]` without calling
8418         // `ChannelManager::accept_inbound_channel`, which generates a
8419         // `MessageSendEvent::SendAcceptChannel` event. The message is passed to `nodes[0]`
8420         // `handle_accept_channel`, which is required in order for `create_funding_transaction` to
8421         // succeed when `nodes[0]` is passed to it.
8422         {
8423                 let mut lock;
8424                 let channel = get_channel_ref!(&nodes[1], lock, temp_channel_id);
8425                 let accept_chan_msg = channel.get_accept_channel_message();
8426                 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8427         }
8428
8429         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8430
8431         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8432         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8433
8434         // The `funding_created_msg` should be rejected by `nodes[1]` as it hasn't accepted the channel
8435         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8436
8437         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8438         assert_eq!(close_msg_ev.len(), 1);
8439
8440         let expected_err = "FundingCreated message received before the channel was accepted";
8441         match close_msg_ev[0] {
8442                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id, } => {
8443                         assert_eq!(msg.channel_id, temp_channel_id);
8444                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8445                         assert_eq!(msg.data, expected_err);
8446                 }
8447                 _ => panic!("Unexpected event"),
8448         }
8449
8450         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
8451 }
8452
8453 #[test]
8454 fn test_can_not_accept_inbound_channel_twice() {
8455         let mut manually_accept_conf = UserConfig::default();
8456         manually_accept_conf.manually_accept_inbound_channels = true;
8457         let chanmon_cfgs = create_chanmon_cfgs(2);
8458         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8459         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8460         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8461
8462         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8463         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8464
8465         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8466
8467         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8468         // accepting the inbound channel request.
8469         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8470
8471         let events = nodes[1].node.get_and_clear_pending_events();
8472         match events[0] {
8473                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8474                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
8475                         let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
8476                         match api_res {
8477                                 Err(APIError::APIMisuseError { err }) => {
8478                                         assert_eq!(err, "The channel isn't currently awaiting to be accepted.");
8479                                 },
8480                                 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
8481                                 Err(_) => panic!("Unexpected Error"),
8482                         }
8483                 }
8484                 _ => panic!("Unexpected event"),
8485         }
8486
8487         // Ensure that the channel wasn't closed after attempting to accept it twice.
8488         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8489         assert_eq!(accept_msg_ev.len(), 1);
8490
8491         match accept_msg_ev[0] {
8492                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8493                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8494                 }
8495                 _ => panic!("Unexpected event"),
8496         }
8497 }
8498
8499 #[test]
8500 fn test_can_not_accept_unknown_inbound_channel() {
8501         let chanmon_cfg = create_chanmon_cfgs(2);
8502         let node_cfg = create_node_cfgs(2, &chanmon_cfg);
8503         let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
8504         let nodes = create_network(2, &node_cfg, &node_chanmgr);
8505
8506         let unknown_channel_id = [0; 32];
8507         let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
8508         match api_res {
8509                 Err(APIError::ChannelUnavailable { err }) => {
8510                         assert_eq!(err, "Can't accept a channel that doesn't exist");
8511                 },
8512                 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
8513                 Err(_) => panic!("Unexpected Error"),
8514         }
8515 }
8516
8517 #[test]
8518 fn test_simple_mpp() {
8519         // Simple test of sending a multi-path payment.
8520         let chanmon_cfgs = create_chanmon_cfgs(4);
8521         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8522         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8523         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8524
8525         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8526         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8527         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8528         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8529
8530         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8531         let path = route.paths[0].clone();
8532         route.paths.push(path);
8533         route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8534         route.paths[0][0].short_channel_id = chan_1_id;
8535         route.paths[0][1].short_channel_id = chan_3_id;
8536         route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8537         route.paths[1][0].short_channel_id = chan_2_id;
8538         route.paths[1][1].short_channel_id = chan_4_id;
8539         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8540         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8541 }
8542
8543 #[test]
8544 fn test_preimage_storage() {
8545         // Simple test of payment preimage storage allowing no client-side storage to claim payments
8546         let chanmon_cfgs = create_chanmon_cfgs(2);
8547         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8548         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8549         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8550
8551         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8552
8553         {
8554                 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200).unwrap();
8555                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8556                 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8557                 check_added_monitors!(nodes[0], 1);
8558                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8559                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8560                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8561                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8562         }
8563         // Note that after leaving the above scope we have no knowledge of any arguments or return
8564         // values from previous calls.
8565         expect_pending_htlcs_forwardable!(nodes[1]);
8566         let events = nodes[1].node.get_and_clear_pending_events();
8567         assert_eq!(events.len(), 1);
8568         match events[0] {
8569                 Event::PaymentReceived { ref purpose, .. } => {
8570                         match &purpose {
8571                                 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
8572                                         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8573                                 },
8574                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
8575                         }
8576                 },
8577                 _ => panic!("Unexpected event"),
8578         }
8579 }
8580
8581 #[test]
8582 #[allow(deprecated)]
8583 fn test_secret_timeout() {
8584         // Simple test of payment secret storage time outs. After
8585         // `create_inbound_payment(_for_hash)_legacy` is removed, this test will be removed as well.
8586         let chanmon_cfgs = create_chanmon_cfgs(2);
8587         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8588         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8589         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8590
8591         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8592
8593         let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment_legacy(Some(100_000), 2).unwrap();
8594
8595         // We should fail to register the same payment hash twice, at least until we've connected a
8596         // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
8597         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8598                 assert_eq!(err, "Duplicate payment hash");
8599         } else { panic!(); }
8600         let mut block = {
8601                 let node_1_blocks = nodes[1].blocks.lock().unwrap();
8602                 Block {
8603                         header: BlockHeader {
8604                                 version: 0x2000000,
8605                                 prev_blockhash: node_1_blocks.last().unwrap().0.block_hash(),
8606                                 merkle_root: Default::default(),
8607                                 time: node_1_blocks.len() as u32 + 7200, bits: 42, nonce: 42 },
8608                         txdata: vec![],
8609                 }
8610         };
8611         connect_block(&nodes[1], &block);
8612         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8613                 assert_eq!(err, "Duplicate payment hash");
8614         } else { panic!(); }
8615
8616         // If we then connect the second block, we should be able to register the same payment hash
8617         // again (this time getting a new payment secret).
8618         block.header.prev_blockhash = block.header.block_hash();
8619         block.header.time += 1;
8620         connect_block(&nodes[1], &block);
8621         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2).unwrap();
8622         assert_ne!(payment_secret_1, our_payment_secret);
8623
8624         {
8625                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8626                 nodes[0].node.send_payment(&route, payment_hash, &Some(our_payment_secret)).unwrap();
8627                 check_added_monitors!(nodes[0], 1);
8628                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8629                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8630                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8631                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8632         }
8633         // Note that after leaving the above scope we have no knowledge of any arguments or return
8634         // values from previous calls.
8635         expect_pending_htlcs_forwardable!(nodes[1]);
8636         let events = nodes[1].node.get_and_clear_pending_events();
8637         assert_eq!(events.len(), 1);
8638         match events[0] {
8639                 Event::PaymentReceived { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret }, .. } => {
8640                         assert!(payment_preimage.is_none());
8641                         assert_eq!(payment_secret, our_payment_secret);
8642                         // We don't actually have the payment preimage with which to claim this payment!
8643                 },
8644                 _ => panic!("Unexpected event"),
8645         }
8646 }
8647
8648 #[test]
8649 fn test_bad_secret_hash() {
8650         // Simple test of unregistered payment hash/invalid payment secret handling
8651         let chanmon_cfgs = create_chanmon_cfgs(2);
8652         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8653         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8654         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8655
8656         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8657
8658         let random_payment_hash = PaymentHash([42; 32]);
8659         let random_payment_secret = PaymentSecret([43; 32]);
8660         let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2).unwrap();
8661         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8662
8663         // All the below cases should end up being handled exactly identically, so we macro the
8664         // resulting events.
8665         macro_rules! handle_unknown_invalid_payment_data {
8666                 () => {
8667                         check_added_monitors!(nodes[0], 1);
8668                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8669                         let payment_event = SendEvent::from_event(events.pop().unwrap());
8670                         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8671                         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8672
8673                         // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8674                         // again to process the pending backwards-failure of the HTLC
8675                         expect_pending_htlcs_forwardable!(nodes[1]);
8676                         expect_pending_htlcs_forwardable!(nodes[1]);
8677                         check_added_monitors!(nodes[1], 1);
8678
8679                         // We should fail the payment back
8680                         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8681                         match events.pop().unwrap() {
8682                                 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8683                                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8684                                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8685                                 },
8686                                 _ => panic!("Unexpected event"),
8687                         }
8688                 }
8689         }
8690
8691         let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8692         // Error data is the HTLC value (100,000) and current block height
8693         let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8694
8695         // Send a payment with the right payment hash but the wrong payment secret
8696         nodes[0].node.send_payment(&route, our_payment_hash, &Some(random_payment_secret)).unwrap();
8697         handle_unknown_invalid_payment_data!();
8698         expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8699
8700         // Send a payment with a random payment hash, but the right payment secret
8701         nodes[0].node.send_payment(&route, random_payment_hash, &Some(our_payment_secret)).unwrap();
8702         handle_unknown_invalid_payment_data!();
8703         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8704
8705         // Send a payment with a random payment hash and random payment secret
8706         nodes[0].node.send_payment(&route, random_payment_hash, &Some(random_payment_secret)).unwrap();
8707         handle_unknown_invalid_payment_data!();
8708         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8709 }
8710
8711 #[test]
8712 fn test_update_err_monitor_lockdown() {
8713         // Our monitor will lock update of local commitment transaction if a broadcastion condition
8714         // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8715         // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
8716         //
8717         // This scenario may happen in a watchtower setup, where watchtower process a block height
8718         // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8719         // commitment at same time.
8720
8721         let chanmon_cfgs = create_chanmon_cfgs(2);
8722         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8723         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8724         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8725
8726         // Create some initial channel
8727         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8728         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8729
8730         // Rebalance the network to generate htlc in the two directions
8731         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8732
8733         // Route a HTLC from node 0 to node 1 (but don't settle)
8734         let preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8735
8736         // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8737         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8738         let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8739         let persister = test_utils::TestPersister::new();
8740         let watchtower = {
8741                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8742                 let mut w = test_utils::TestVecWriter(Vec::new());
8743                 monitor.write(&mut w).unwrap();
8744                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8745                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8746                 assert!(new_monitor == *monitor);
8747                 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);
8748                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8749                 watchtower
8750         };
8751         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8752         let block = Block { header, txdata: vec![] };
8753         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8754         // transaction lock time requirements here.
8755         chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 0));
8756         watchtower.chain_monitor.block_connected(&block, 200);
8757
8758         // Try to update ChannelMonitor
8759         assert!(nodes[1].node.claim_funds(preimage));
8760         check_added_monitors!(nodes[1], 1);
8761         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8762         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8763         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8764         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8765                 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8766                         if let Err(_) =  watchtower.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8767                         if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8768                 } else { assert!(false); }
8769         } else { assert!(false); };
8770         // Our local monitor is in-sync and hasn't processed yet timeout
8771         check_added_monitors!(nodes[0], 1);
8772         let events = nodes[0].node.get_and_clear_pending_events();
8773         assert_eq!(events.len(), 1);
8774 }
8775
8776 #[test]
8777 fn test_concurrent_monitor_claim() {
8778         // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8779         // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8780         // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8781         // state N+1 confirms. Alice claims output from state N+1.
8782
8783         let chanmon_cfgs = create_chanmon_cfgs(2);
8784         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8785         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8786         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8787
8788         // Create some initial channel
8789         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8790         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8791
8792         // Rebalance the network to generate htlc in the two directions
8793         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8794
8795         // Route a HTLC from node 0 to node 1 (but don't settle)
8796         route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8797
8798         // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8799         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8800         let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8801         let persister = test_utils::TestPersister::new();
8802         let watchtower_alice = {
8803                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8804                 let mut w = test_utils::TestVecWriter(Vec::new());
8805                 monitor.write(&mut w).unwrap();
8806                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8807                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8808                 assert!(new_monitor == *monitor);
8809                 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);
8810                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8811                 watchtower
8812         };
8813         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8814         let block = Block { header, txdata: vec![] };
8815         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8816         // transaction lock time requirements here.
8817         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));
8818         watchtower_alice.chain_monitor.block_connected(&block, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8819
8820         // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8821         {
8822                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8823                 assert_eq!(txn.len(), 2);
8824                 txn.clear();
8825         }
8826
8827         // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8828         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8829         let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8830         let persister = test_utils::TestPersister::new();
8831         let watchtower_bob = {
8832                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8833                 let mut w = test_utils::TestVecWriter(Vec::new());
8834                 monitor.write(&mut w).unwrap();
8835                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8836                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8837                 assert!(new_monitor == *monitor);
8838                 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);
8839                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8840                 watchtower
8841         };
8842         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8843         watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8844
8845         // Route another payment to generate another update with still previous HTLC pending
8846         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8847         {
8848                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8849         }
8850         check_added_monitors!(nodes[1], 1);
8851
8852         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8853         assert_eq!(updates.update_add_htlcs.len(), 1);
8854         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8855         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8856                 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8857                         // Watchtower Alice should already have seen the block and reject the update
8858                         if let Err(_) =  watchtower_alice.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8859                         if let Ok(_) = watchtower_bob.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8860                         if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8861                 } else { assert!(false); }
8862         } else { assert!(false); };
8863         // Our local monitor is in-sync and hasn't processed yet timeout
8864         check_added_monitors!(nodes[0], 1);
8865
8866         //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8867         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8868         watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8869
8870         // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8871         let bob_state_y;
8872         {
8873                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8874                 assert_eq!(txn.len(), 2);
8875                 bob_state_y = txn[0].clone();
8876                 txn.clear();
8877         };
8878
8879         // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8880         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8881         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);
8882         {
8883                 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8884                 // We broadcast twice the transaction, once due to the HTLC-timeout, once due
8885                 // the onchain detection of the HTLC output
8886                 assert_eq!(htlc_txn.len(), 2);
8887                 check_spends!(htlc_txn[0], bob_state_y);
8888                 check_spends!(htlc_txn[1], bob_state_y);
8889         }
8890 }
8891
8892 #[test]
8893 fn test_pre_lockin_no_chan_closed_update() {
8894         // Test that if a peer closes a channel in response to a funding_created message we don't
8895         // generate a channel update (as the channel cannot appear on chain without a funding_signed
8896         // message).
8897         //
8898         // Doing so would imply a channel monitor update before the initial channel monitor
8899         // registration, violating our API guarantees.
8900         //
8901         // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8902         // then opening a second channel with the same funding output as the first (which is not
8903         // rejected because the first channel does not exist in the ChannelManager) and closing it
8904         // before receiving funding_signed.
8905         let chanmon_cfgs = create_chanmon_cfgs(2);
8906         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8907         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8908         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8909
8910         // Create an initial channel
8911         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8912         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8913         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8914         let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8915         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8916
8917         // Move the first channel through the funding flow...
8918         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8919
8920         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8921         check_added_monitors!(nodes[0], 0);
8922
8923         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8924         let channel_id = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8925         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8926         assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8927         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "Hi".to_string() }, true);
8928 }
8929
8930 #[test]
8931 fn test_htlc_no_detection() {
8932         // This test is a mutation to underscore the detection logic bug we had
8933         // before #653. HTLC value routed is above the remaining balance, thus
8934         // inverting HTLC and `to_remote` output. HTLC will come second and
8935         // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8936         // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8937         // outputs order detection for correct spending children filtring.
8938
8939         let chanmon_cfgs = create_chanmon_cfgs(2);
8940         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8941         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8942         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8943
8944         // Create some initial channels
8945         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8946
8947         send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8948         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8949         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8950         assert_eq!(local_txn[0].input.len(), 1);
8951         assert_eq!(local_txn[0].output.len(), 3);
8952         check_spends!(local_txn[0], chan_1.3);
8953
8954         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8955         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8956         connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] });
8957         // We deliberately connect the local tx twice as this should provoke a failure calling
8958         // this test before #653 fix.
8959         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);
8960         check_closed_broadcast!(nodes[0], true);
8961         check_added_monitors!(nodes[0], 1);
8962         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8963         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1);
8964
8965         let htlc_timeout = {
8966                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8967                 assert_eq!(node_txn[1].input.len(), 1);
8968                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8969                 check_spends!(node_txn[1], local_txn[0]);
8970                 node_txn[1].clone()
8971         };
8972
8973         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8974         connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] });
8975         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8976         expect_payment_failed!(nodes[0], our_payment_hash, true);
8977 }
8978
8979 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8980         // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8981         // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8982         // Carol, Alice would be the upstream node, and Carol the downstream.)
8983         //
8984         // Steps of the test:
8985         // 1) Alice sends a HTLC to Carol through Bob.
8986         // 2) Carol doesn't settle the HTLC.
8987         // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8988         // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8989         // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8990         //    but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8991         // 5) Carol release the preimage to Bob off-chain.
8992         // 6) Bob claims the offered output on the broadcasted commitment.
8993         let chanmon_cfgs = create_chanmon_cfgs(3);
8994         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8995         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8996         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8997
8998         // Create some initial channels
8999         let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9000         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9001
9002         // Steps (1) and (2):
9003         // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
9004         let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3_000_000);
9005
9006         // Check that Alice's commitment transaction now contains an output for this HTLC.
9007         let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
9008         check_spends!(alice_txn[0], chan_ab.3);
9009         assert_eq!(alice_txn[0].output.len(), 2);
9010         check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
9011         assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9012         assert_eq!(alice_txn.len(), 2);
9013
9014         // Steps (3) and (4):
9015         // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
9016         // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
9017         let mut force_closing_node = 0; // Alice force-closes
9018         let mut counterparty_node = 1; // Bob if Alice force-closes
9019
9020         // Bob force-closes
9021         if !broadcast_alice {
9022                 force_closing_node = 1;
9023                 counterparty_node = 0;
9024         }
9025         nodes[force_closing_node].node.force_close_channel(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id()).unwrap();
9026         check_closed_broadcast!(nodes[force_closing_node], true);
9027         check_added_monitors!(nodes[force_closing_node], 1);
9028         check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
9029         if go_onchain_before_fulfill {
9030                 let txn_to_broadcast = match broadcast_alice {
9031                         true => alice_txn.clone(),
9032                         false => get_local_commitment_txn!(nodes[1], chan_ab.2)
9033                 };
9034                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
9035                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
9036                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
9037                 if broadcast_alice {
9038                         check_closed_broadcast!(nodes[1], true);
9039                         check_added_monitors!(nodes[1], 1);
9040                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
9041                 }
9042                 assert_eq!(bob_txn.len(), 1);
9043                 check_spends!(bob_txn[0], chan_ab.3);
9044         }
9045
9046         // Step (5):
9047         // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
9048         // process of removing the HTLC from their commitment transactions.
9049         assert!(nodes[2].node.claim_funds(payment_preimage));
9050         check_added_monitors!(nodes[2], 1);
9051         let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
9052         assert!(carol_updates.update_add_htlcs.is_empty());
9053         assert!(carol_updates.update_fail_htlcs.is_empty());
9054         assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
9055         assert!(carol_updates.update_fee.is_none());
9056         assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
9057
9058         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
9059         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false, false);
9060         // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
9061         if !go_onchain_before_fulfill && broadcast_alice {
9062                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9063                 assert_eq!(events.len(), 1);
9064                 match events[0] {
9065                         MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
9066                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9067                         },
9068                         _ => panic!("Unexpected event"),
9069                 };
9070         }
9071         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
9072         // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
9073         // Carol<->Bob's updated commitment transaction info.
9074         check_added_monitors!(nodes[1], 2);
9075
9076         let events = nodes[1].node.get_and_clear_pending_msg_events();
9077         assert_eq!(events.len(), 2);
9078         let bob_revocation = match events[0] {
9079                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
9080                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
9081                         (*msg).clone()
9082                 },
9083                 _ => panic!("Unexpected event"),
9084         };
9085         let bob_updates = match events[1] {
9086                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
9087                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
9088                         (*updates).clone()
9089                 },
9090                 _ => panic!("Unexpected event"),
9091         };
9092
9093         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
9094         check_added_monitors!(nodes[2], 1);
9095         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
9096         check_added_monitors!(nodes[2], 1);
9097
9098         let events = nodes[2].node.get_and_clear_pending_msg_events();
9099         assert_eq!(events.len(), 1);
9100         let carol_revocation = match events[0] {
9101                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
9102                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
9103                         (*msg).clone()
9104                 },
9105                 _ => panic!("Unexpected event"),
9106         };
9107         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
9108         check_added_monitors!(nodes[1], 1);
9109
9110         // If this test requires the force-closed channel to not be on-chain until after the fulfill,
9111         // here's where we put said channel's commitment tx on-chain.
9112         let mut txn_to_broadcast = alice_txn.clone();
9113         if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
9114         if !go_onchain_before_fulfill {
9115                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
9116                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
9117                 // If Bob was the one to force-close, he will have already passed these checks earlier.
9118                 if broadcast_alice {
9119                         check_closed_broadcast!(nodes[1], true);
9120                         check_added_monitors!(nodes[1], 1);
9121                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
9122                 }
9123                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9124                 if broadcast_alice {
9125                         // In `connect_block()`, the ChainMonitor and ChannelManager are separately notified about a
9126                         // new block being connected. The ChannelManager being notified triggers a monitor update,
9127                         // which triggers broadcasting our commitment tx and an HTLC-claiming tx. The ChainMonitor
9128                         // being notified triggers the HTLC-claiming tx redundantly, resulting in 3 total txs being
9129                         // broadcasted.
9130                         assert_eq!(bob_txn.len(), 3);
9131                         check_spends!(bob_txn[1], chan_ab.3);
9132                 } else {
9133                         assert_eq!(bob_txn.len(), 2);
9134                         check_spends!(bob_txn[0], chan_ab.3);
9135                 }
9136         }
9137
9138         // Step (6):
9139         // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
9140         // broadcasted commitment transaction.
9141         {
9142                 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
9143                 if go_onchain_before_fulfill {
9144                         // Bob should now have an extra broadcasted tx, for the preimage-claiming transaction.
9145                         assert_eq!(bob_txn.len(), 2);
9146                 }
9147                 let script_weight = match broadcast_alice {
9148                         true => OFFERED_HTLC_SCRIPT_WEIGHT,
9149                         false => ACCEPTED_HTLC_SCRIPT_WEIGHT
9150                 };
9151                 // If Alice force-closed and Bob didn't receive her commitment transaction until after he
9152                 // received Carol's fulfill, he broadcasts the HTLC-output-claiming transaction first. Else if
9153                 // Bob force closed or if he found out about Alice's commitment tx before receiving Carol's
9154                 // fulfill, then he broadcasts the HTLC-output-claiming transaction second.
9155                 if broadcast_alice && !go_onchain_before_fulfill {
9156                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
9157                         assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
9158                 } else {
9159                         check_spends!(bob_txn[1], txn_to_broadcast[0]);
9160                         assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
9161                 }
9162         }
9163 }
9164
9165 #[test]
9166 fn test_onchain_htlc_settlement_after_close() {
9167         do_test_onchain_htlc_settlement_after_close(true, true);
9168         do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
9169         do_test_onchain_htlc_settlement_after_close(true, false);
9170         do_test_onchain_htlc_settlement_after_close(false, false);
9171 }
9172
9173 #[test]
9174 fn test_duplicate_chan_id() {
9175         // Test that if a given peer tries to open a channel with the same channel_id as one that is
9176         // already open we reject it and keep the old channel.
9177         //
9178         // Previously, full_stack_target managed to figure out that if you tried to open two channels
9179         // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
9180         // the existing channel when we detect the duplicate new channel, screwing up our monitor
9181         // updating logic for the existing channel.
9182         let chanmon_cfgs = create_chanmon_cfgs(2);
9183         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9184         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9185         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9186
9187         // Create an initial channel
9188         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9189         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9190         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9191         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()));
9192
9193         // Try to create a second channel with the same temporary_channel_id as the first and check
9194         // that it is rejected.
9195         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9196         {
9197                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9198                 assert_eq!(events.len(), 1);
9199                 match events[0] {
9200                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9201                                 // Technically, at this point, nodes[1] would be justified in thinking both the
9202                                 // first (valid) and second (invalid) channels are closed, given they both have
9203                                 // the same non-temporary channel_id. However, currently we do not, so we just
9204                                 // move forward with it.
9205                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9206                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9207                         },
9208                         _ => panic!("Unexpected event"),
9209                 }
9210         }
9211
9212         // Move the first channel through the funding flow...
9213         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
9214
9215         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9216         check_added_monitors!(nodes[0], 0);
9217
9218         let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9219         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
9220         {
9221                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
9222                 assert_eq!(added_monitors.len(), 1);
9223                 assert_eq!(added_monitors[0].0, funding_output);
9224                 added_monitors.clear();
9225         }
9226         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9227
9228         let funding_outpoint = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
9229         let channel_id = funding_outpoint.to_channel_id();
9230
9231         // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
9232         // temporary one).
9233
9234         // First try to open a second channel with a temporary channel id equal to the txid-based one.
9235         // Technically this is allowed by the spec, but we don't support it and there's little reason
9236         // to. Still, it shouldn't cause any other issues.
9237         open_chan_msg.temporary_channel_id = channel_id;
9238         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9239         {
9240                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9241                 assert_eq!(events.len(), 1);
9242                 match events[0] {
9243                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9244                                 // Technically, at this point, nodes[1] would be justified in thinking both
9245                                 // channels are closed, but currently we do not, so we just move forward with it.
9246                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9247                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9248                         },
9249                         _ => panic!("Unexpected event"),
9250                 }
9251         }
9252
9253         // Now try to create a second channel which has a duplicate funding output.
9254         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9255         let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9256         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_2_msg);
9257         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()));
9258         create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
9259
9260         let funding_created = {
9261                 let mut a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
9262                 let mut as_chan = a_channel_lock.by_id.get_mut(&open_chan_2_msg.temporary_channel_id).unwrap();
9263                 let logger = test_utils::TestLogger::new();
9264                 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
9265         };
9266         check_added_monitors!(nodes[0], 0);
9267         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
9268         // At this point we'll try to add a duplicate channel monitor, which will be rejected, but
9269         // still needs to be cleared here.
9270         check_added_monitors!(nodes[1], 1);
9271
9272         // ...still, nodes[1] will reject the duplicate channel.
9273         {
9274                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9275                 assert_eq!(events.len(), 1);
9276                 match events[0] {
9277                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9278                                 // Technically, at this point, nodes[1] would be justified in thinking both
9279                                 // channels are closed, but currently we do not, so we just move forward with it.
9280                                 assert_eq!(msg.channel_id, channel_id);
9281                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9282                         },
9283                         _ => panic!("Unexpected event"),
9284                 }
9285         }
9286
9287         // finally, finish creating the original channel and send a payment over it to make sure
9288         // everything is functional.
9289         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
9290         {
9291                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9292                 assert_eq!(added_monitors.len(), 1);
9293                 assert_eq!(added_monitors[0].0, funding_output);
9294                 added_monitors.clear();
9295         }
9296
9297         let events_4 = nodes[0].node.get_and_clear_pending_events();
9298         assert_eq!(events_4.len(), 0);
9299         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9300         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
9301
9302         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9303         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
9304         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9305         send_payment(&nodes[0], &[&nodes[1]], 8000000);
9306 }
9307
9308 #[test]
9309 fn test_error_chans_closed() {
9310         // Test that we properly handle error messages, closing appropriate channels.
9311         //
9312         // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
9313         // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
9314         // we can test various edge cases around it to ensure we don't regress.
9315         let chanmon_cfgs = create_chanmon_cfgs(3);
9316         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9317         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9318         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9319
9320         // Create some initial channels
9321         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9322         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9323         let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9324
9325         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9326         assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
9327         assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
9328
9329         // Closing a channel from a different peer has no effect
9330         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
9331         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9332
9333         // Closing one channel doesn't impact others
9334         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
9335         check_added_monitors!(nodes[0], 1);
9336         check_closed_broadcast!(nodes[0], false);
9337         check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
9338         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
9339         assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
9340         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);
9341         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);
9342
9343         // A null channel ID should close all channels
9344         let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9345         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
9346         check_added_monitors!(nodes[0], 2);
9347         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
9348         let events = nodes[0].node.get_and_clear_pending_msg_events();
9349         assert_eq!(events.len(), 2);
9350         match events[0] {
9351                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9352                         assert_eq!(msg.contents.flags & 2, 2);
9353                 },
9354                 _ => panic!("Unexpected event"),
9355         }
9356         match events[1] {
9357                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9358                         assert_eq!(msg.contents.flags & 2, 2);
9359                 },
9360                 _ => panic!("Unexpected event"),
9361         }
9362         // Note that at this point users of a standard PeerHandler will end up calling
9363         // peer_disconnected with no_connection_possible set to false, duplicating the
9364         // close-all-channels logic. That's OK, we don't want to end up not force-closing channels for
9365         // users with their own peer handling logic. We duplicate the call here, however.
9366         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9367         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9368
9369         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
9370         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9371         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9372 }
9373
9374 #[test]
9375 fn test_invalid_funding_tx() {
9376         // Test that we properly handle invalid funding transactions sent to us from a peer.
9377         //
9378         // Previously, all other major lightning implementations had failed to properly sanitize
9379         // funding transactions from their counterparties, leading to a multi-implementation critical
9380         // security vulnerability (though we always sanitized properly, we've previously had
9381         // un-released crashes in the sanitization process).
9382         let chanmon_cfgs = create_chanmon_cfgs(2);
9383         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9384         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9385         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9386
9387         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
9388         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()));
9389         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()));
9390
9391         let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
9392         for output in tx.output.iter_mut() {
9393                 // Make the confirmed funding transaction have a bogus script_pubkey
9394                 output.script_pubkey = bitcoin::Script::new();
9395         }
9396
9397         nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
9398         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()));
9399         check_added_monitors!(nodes[1], 1);
9400
9401         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()));
9402         check_added_monitors!(nodes[0], 1);
9403
9404         let events_1 = nodes[0].node.get_and_clear_pending_events();
9405         assert_eq!(events_1.len(), 0);
9406
9407         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9408         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9409         nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9410
9411         let expected_err = "funding tx had wrong script/value or output index";
9412         confirm_transaction_at(&nodes[1], &tx, 1);
9413         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
9414         check_added_monitors!(nodes[1], 1);
9415         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9416         assert_eq!(events_2.len(), 1);
9417         if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9418                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9419                 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
9420                         assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
9421                 } else { panic!(); }
9422         } else { panic!(); }
9423         assert_eq!(nodes[1].node.list_channels().len(), 0);
9424 }
9425
9426 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9427         // In the first version of the chain::Confirm interface, after a refactor was made to not
9428         // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9429         // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9430         // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9431         // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9432         // spending transaction until height N+1 (or greater). This was due to the way
9433         // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9434         // spending transaction at the height the input transaction was confirmed at, not whether we
9435         // should broadcast a spending transaction at the current height.
9436         // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9437         // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9438         // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9439         // until we learned about an additional block.
9440         //
9441         // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9442         // aren't broadcasting transactions too early (ie not broadcasting them at all).
9443         let chanmon_cfgs = create_chanmon_cfgs(3);
9444         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9445         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9446         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9447         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9448
9449         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
9450         let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
9451         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9452         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
9453         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9454
9455         nodes[1].node.force_close_channel(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
9456         check_closed_broadcast!(nodes[1], true);
9457         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
9458         check_added_monitors!(nodes[1], 1);
9459         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9460         assert_eq!(node_txn.len(), 1);
9461
9462         let conf_height = nodes[1].best_block_info().1;
9463         if !test_height_before_timelock {
9464                 connect_blocks(&nodes[1], 24 * 6);
9465         }
9466         nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9467                 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9468         if test_height_before_timelock {
9469                 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9470                 // generate any events or broadcast any transactions
9471                 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9472                 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9473         } else {
9474                 // We should broadcast an HTLC transaction spending our funding transaction first
9475                 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9476                 assert_eq!(spending_txn.len(), 2);
9477                 assert_eq!(spending_txn[0], node_txn[0]);
9478                 check_spends!(spending_txn[1], node_txn[0]);
9479                 // We should also generate a SpendableOutputs event with the to_self output (as its
9480                 // timelock is up).
9481                 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9482                 assert_eq!(descriptor_spend_txn.len(), 1);
9483
9484                 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9485                 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9486                 // additional block built on top of the current chain.
9487                 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9488                         &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9489                 expect_pending_htlcs_forwardable!(nodes[1]);
9490                 check_added_monitors!(nodes[1], 1);
9491
9492                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9493                 assert!(updates.update_add_htlcs.is_empty());
9494                 assert!(updates.update_fulfill_htlcs.is_empty());
9495                 assert_eq!(updates.update_fail_htlcs.len(), 1);
9496                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9497                 assert!(updates.update_fee.is_none());
9498                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9499                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9500                 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9501         }
9502 }
9503
9504 #[test]
9505 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9506         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9507         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9508 }
9509
9510 #[test]
9511 fn test_forwardable_regen() {
9512         // Tests that if we reload a ChannelManager while forwards are pending we will regenerate the
9513         // PendingHTLCsForwardable event automatically, ensuring we don't forget to forward/receive
9514         // HTLCs.
9515         // We test it for both payment receipt and payment forwarding.
9516
9517         let chanmon_cfgs = create_chanmon_cfgs(3);
9518         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9519         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9520         let persister: test_utils::TestPersister;
9521         let new_chain_monitor: test_utils::TestChainMonitor;
9522         let nodes_1_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
9523         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9524         let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
9525         let chan_id_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known()).2;
9526
9527         // First send a payment to nodes[1]
9528         let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
9529         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
9530         check_added_monitors!(nodes[0], 1);
9531
9532         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9533         assert_eq!(events.len(), 1);
9534         let payment_event = SendEvent::from_event(events.pop().unwrap());
9535         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9536         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9537
9538         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9539
9540         // Next send a payment which is forwarded by nodes[1]
9541         let (route_2, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 200_000);
9542         nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
9543         check_added_monitors!(nodes[0], 1);
9544
9545         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9546         assert_eq!(events.len(), 1);
9547         let payment_event = SendEvent::from_event(events.pop().unwrap());
9548         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9549         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9550
9551         // There is already a PendingHTLCsForwardable event "pending" so another one will not be
9552         // generated
9553         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
9554
9555         // Now restart nodes[1] and make sure it regenerates a single PendingHTLCsForwardable
9556         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9557         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9558
9559         let nodes_1_serialized = nodes[1].node.encode();
9560         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9561         let mut chan_1_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9562         get_monitor!(nodes[1], chan_id_1).write(&mut chan_0_monitor_serialized).unwrap();
9563         get_monitor!(nodes[1], chan_id_2).write(&mut chan_1_monitor_serialized).unwrap();
9564
9565         persister = test_utils::TestPersister::new();
9566         let keys_manager = &chanmon_cfgs[1].keys_manager;
9567         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);
9568         nodes[1].chain_monitor = &new_chain_monitor;
9569
9570         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
9571         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9572                 &mut chan_0_monitor_read, keys_manager).unwrap();
9573         assert!(chan_0_monitor_read.is_empty());
9574         let mut chan_1_monitor_read = &chan_1_monitor_serialized.0[..];
9575         let (_, mut chan_1_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9576                 &mut chan_1_monitor_read, keys_manager).unwrap();
9577         assert!(chan_1_monitor_read.is_empty());
9578
9579         let mut nodes_1_read = &nodes_1_serialized[..];
9580         let (_, nodes_1_deserialized_tmp) = {
9581                 let mut channel_monitors = HashMap::new();
9582                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
9583                 channel_monitors.insert(chan_1_monitor.get_funding_txo().0, &mut chan_1_monitor);
9584                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_1_read, ChannelManagerReadArgs {
9585                         default_config: UserConfig::default(),
9586                         keys_manager,
9587                         fee_estimator: node_cfgs[1].fee_estimator,
9588                         chain_monitor: nodes[1].chain_monitor,
9589                         tx_broadcaster: nodes[1].tx_broadcaster.clone(),
9590                         logger: nodes[1].logger,
9591                         channel_monitors,
9592                 }).unwrap()
9593         };
9594         nodes_1_deserialized = nodes_1_deserialized_tmp;
9595         assert!(nodes_1_read.is_empty());
9596
9597         assert!(nodes[1].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
9598         assert!(nodes[1].chain_monitor.watch_channel(chan_1_monitor.get_funding_txo().0, chan_1_monitor).is_ok());
9599         nodes[1].node = &nodes_1_deserialized;
9600         check_added_monitors!(nodes[1], 2);
9601
9602         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9603         // Note that nodes[1] and nodes[2] resend their funding_locked here since they haven't updated
9604         // the commitment state.
9605         reconnect_nodes(&nodes[1], &nodes[2], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9606
9607         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
9608
9609         expect_pending_htlcs_forwardable!(nodes[1]);
9610         expect_payment_received!(nodes[1], payment_hash, payment_secret, 100_000);
9611         check_added_monitors!(nodes[1], 1);
9612
9613         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9614         assert_eq!(events.len(), 1);
9615         let payment_event = SendEvent::from_event(events.pop().unwrap());
9616         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9617         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false);
9618         expect_pending_htlcs_forwardable!(nodes[2]);
9619         expect_payment_received!(nodes[2], payment_hash_2, payment_secret_2, 200_000);
9620
9621         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
9622         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage_2);
9623 }
9624
9625 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
9626         let chanmon_cfgs = create_chanmon_cfgs(2);
9627         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9628         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9629         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9630
9631         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9632
9633         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
9634                 .with_features(InvoiceFeatures::known());
9635         let route = get_route!(nodes[0], payment_params, 10_000, TEST_FINAL_CLTV).unwrap();
9636
9637         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9638
9639         {
9640                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
9641                 check_added_monitors!(nodes[0], 1);
9642                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9643                 assert_eq!(events.len(), 1);
9644                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9645                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9646                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9647         }
9648         expect_pending_htlcs_forwardable!(nodes[1]);
9649         expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9650
9651         {
9652                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
9653                 check_added_monitors!(nodes[0], 1);
9654                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9655                 assert_eq!(events.len(), 1);
9656                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9657                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9658                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9659                 // At this point, nodes[1] would notice it has too much value for the payment. It will
9660                 // assume the second is a privacy attack (no longer particularly relevant
9661                 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9662                 // the first HTLC delivered above.
9663         }
9664
9665         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9666         nodes[1].node.process_pending_htlc_forwards();
9667
9668         if test_for_second_fail_panic {
9669                 // Now we go fail back the first HTLC from the user end.
9670                 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9671
9672                 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9673                 nodes[1].node.process_pending_htlc_forwards();
9674
9675                 check_added_monitors!(nodes[1], 1);
9676                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9677                 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9678
9679                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9680                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9681                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9682
9683                 let failure_events = nodes[0].node.get_and_clear_pending_events();
9684                 assert_eq!(failure_events.len(), 2);
9685                 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9686                 if let Event::PaymentPathFailed { .. } = failure_events[1] {} else { panic!(); }
9687         } else {
9688                 // Let the second HTLC fail and claim the first
9689                 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9690                 nodes[1].node.process_pending_htlc_forwards();
9691
9692                 check_added_monitors!(nodes[1], 1);
9693                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9694                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9695                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9696
9697                 expect_payment_failed_conditions!(nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9698
9699                 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9700         }
9701 }
9702
9703 #[test]
9704 fn test_dup_htlc_second_fail_panic() {
9705         // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9706         // value for the payment, we'd fail back both HTLCs after generating a `PaymentReceived` event.
9707         // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9708         // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9709         do_test_dup_htlc_second_rejected(true);
9710 }
9711
9712 #[test]
9713 fn test_dup_htlc_second_rejected() {
9714         // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9715         // simply reject the second HTLC but are still able to claim the first HTLC.
9716         do_test_dup_htlc_second_rejected(false);
9717 }
9718
9719 #[test]
9720 fn test_inconsistent_mpp_params() {
9721         // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9722         // such HTLC and allow the second to stay.
9723         let chanmon_cfgs = create_chanmon_cfgs(4);
9724         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9725         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9726         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9727
9728         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9729         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9730         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9731         create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9732
9733         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id())
9734                 .with_features(InvoiceFeatures::known());
9735         let mut route = get_route!(nodes[0], payment_params, 15_000_000, TEST_FINAL_CLTV).unwrap();
9736         assert_eq!(route.paths.len(), 2);
9737         route.paths.sort_by(|path_a, _| {
9738                 // Sort the path so that the path through nodes[1] comes first
9739                 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
9740                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9741         });
9742         let payment_params_opt = Some(payment_params);
9743
9744         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9745
9746         let cur_height = nodes[0].best_block_info().1;
9747         let payment_id = PaymentId([42; 32]);
9748         {
9749                 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();
9750                 check_added_monitors!(nodes[0], 1);
9751
9752                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9753                 assert_eq!(events.len(), 1);
9754                 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9755         }
9756         assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9757
9758         {
9759                 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();
9760                 check_added_monitors!(nodes[0], 1);
9761
9762                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9763                 assert_eq!(events.len(), 1);
9764                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9765
9766                 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9767                 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9768
9769                 expect_pending_htlcs_forwardable!(nodes[2]);
9770                 check_added_monitors!(nodes[2], 1);
9771
9772                 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9773                 assert_eq!(events.len(), 1);
9774                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9775
9776                 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9777                 check_added_monitors!(nodes[3], 0);
9778                 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9779
9780                 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9781                 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9782                 // post-payment_secrets) and fail back the new HTLC.
9783         }
9784         expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9785         nodes[3].node.process_pending_htlc_forwards();
9786         expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9787         nodes[3].node.process_pending_htlc_forwards();
9788
9789         check_added_monitors!(nodes[3], 1);
9790
9791         let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9792         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9793         commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9794
9795         expect_pending_htlcs_forwardable!(nodes[2]);
9796         check_added_monitors!(nodes[2], 1);
9797
9798         let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9799         nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9800         commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9801
9802         expect_payment_failed_conditions!(nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9803
9804         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();
9805         check_added_monitors!(nodes[0], 1);
9806
9807         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9808         assert_eq!(events.len(), 1);
9809         pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9810
9811         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9812 }
9813
9814 #[test]
9815 fn test_keysend_payments_to_public_node() {
9816         let chanmon_cfgs = create_chanmon_cfgs(2);
9817         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9818         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9819         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9820
9821         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9822         let network_graph = nodes[0].network_graph;
9823         let payer_pubkey = nodes[0].node.get_our_node_id();
9824         let payee_pubkey = nodes[1].node.get_our_node_id();
9825         let route_params = RouteParameters {
9826                 payment_params: PaymentParameters::for_keysend(payee_pubkey),
9827                 final_value_msat: 10000,
9828                 final_cltv_expiry_delta: 40,
9829         };
9830         let scorer = test_utils::TestScorer::with_penalty(0);
9831         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9832         let route = find_route(&payer_pubkey, &route_params, network_graph, None, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
9833
9834         let test_preimage = PaymentPreimage([42; 32]);
9835         let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9836         check_added_monitors!(nodes[0], 1);
9837         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9838         assert_eq!(events.len(), 1);
9839         let event = events.pop().unwrap();
9840         let path = vec![&nodes[1]];
9841         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9842         claim_payment(&nodes[0], &path, test_preimage);
9843 }
9844
9845 #[test]
9846 fn test_keysend_payments_to_private_node() {
9847         let chanmon_cfgs = create_chanmon_cfgs(2);
9848         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9849         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9850         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9851
9852         let payer_pubkey = nodes[0].node.get_our_node_id();
9853         let payee_pubkey = nodes[1].node.get_our_node_id();
9854         nodes[0].node.peer_connected(&payee_pubkey, &msgs::Init { features: InitFeatures::known(), remote_network_address: None });
9855         nodes[1].node.peer_connected(&payer_pubkey, &msgs::Init { features: InitFeatures::known(), remote_network_address: None });
9856
9857         let _chan = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
9858         let route_params = RouteParameters {
9859                 payment_params: PaymentParameters::for_keysend(payee_pubkey),
9860                 final_value_msat: 10000,
9861                 final_cltv_expiry_delta: 40,
9862         };
9863         let network_graph = nodes[0].network_graph;
9864         let first_hops = nodes[0].node.list_usable_channels();
9865         let scorer = test_utils::TestScorer::with_penalty(0);
9866         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9867         let route = find_route(
9868                 &payer_pubkey, &route_params, network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
9869                 nodes[0].logger, &scorer, &random_seed_bytes
9870         ).unwrap();
9871
9872         let test_preimage = PaymentPreimage([42; 32]);
9873         let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9874         check_added_monitors!(nodes[0], 1);
9875         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9876         assert_eq!(events.len(), 1);
9877         let event = events.pop().unwrap();
9878         let path = vec![&nodes[1]];
9879         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9880         claim_payment(&nodes[0], &path, test_preimage);
9881 }
9882
9883 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
9884 #[derive(Clone, Copy, PartialEq)]
9885 enum ExposureEvent {
9886         /// Breach occurs at HTLC forwarding (see `send_htlc`)
9887         AtHTLCForward,
9888         /// Breach occurs at HTLC reception (see `update_add_htlc`)
9889         AtHTLCReception,
9890         /// Breach occurs at outbound update_fee (see `send_update_fee`)
9891         AtUpdateFeeOutbound,
9892 }
9893
9894 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool) {
9895         // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
9896         // policy.
9897         //
9898         // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
9899         // trimmed-to-dust HTLC outbound balance and this new payment as included on next
9900         // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
9901         // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
9902         // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
9903         // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
9904         // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
9905         // might be available again for HTLC processing once the dust bandwidth has cleared up.
9906
9907         let chanmon_cfgs = create_chanmon_cfgs(2);
9908         let mut config = test_default_channel_config();
9909         config.channel_options.max_dust_htlc_exposure_msat = 5_000_000; // default setting value
9910         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9911         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
9912         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9913
9914         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
9915         let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9916         open_channel.max_htlc_value_in_flight_msat = 50_000_000;
9917         open_channel.max_accepted_htlcs = 60;
9918         if on_holder_tx {
9919                 open_channel.dust_limit_satoshis = 546;
9920         }
9921         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
9922         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9923         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
9924
9925         let opt_anchors = false;
9926
9927         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
9928
9929         if on_holder_tx {
9930                 if let Some(mut chan) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&temporary_channel_id) {
9931                         chan.holder_dust_limit_satoshis = 546;
9932                 }
9933         }
9934
9935         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9936         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()));
9937         check_added_monitors!(nodes[1], 1);
9938
9939         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()));
9940         check_added_monitors!(nodes[0], 1);
9941
9942         let (funding_locked, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9943         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
9944         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9945
9946         let dust_buffer_feerate = {
9947                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
9948                 let chan = chan_lock.by_id.get(&channel_id).unwrap();
9949                 chan.get_dust_buffer_feerate(None) as u64
9950         };
9951         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;
9952         let dust_outbound_htlc_on_holder_tx: u64 = config.channel_options.max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
9953
9954         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;
9955         let dust_inbound_htlc_on_holder_tx: u64 = config.channel_options.max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
9956
9957         let dust_htlc_on_counterparty_tx: u64 = 25;
9958         let dust_htlc_on_counterparty_tx_msat: u64 = config.channel_options.max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
9959
9960         if on_holder_tx {
9961                 if dust_outbound_balance {
9962                         // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9963                         // Outbound dust balance: 4372 sats
9964                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
9965                         for i in 0..dust_outbound_htlc_on_holder_tx {
9966                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
9967                                 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at dust HTLC {}", i); }
9968                         }
9969                 } else {
9970                         // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9971                         // Inbound dust balance: 4372 sats
9972                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
9973                         for _ in 0..dust_inbound_htlc_on_holder_tx {
9974                                 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
9975                         }
9976                 }
9977         } else {
9978                 if dust_outbound_balance {
9979                         // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9980                         // Outbound dust balance: 5000 sats
9981                         for i in 0..dust_htlc_on_counterparty_tx {
9982                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
9983                                 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at dust HTLC {}", i); }
9984                         }
9985                 } else {
9986                         // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9987                         // Inbound dust balance: 5000 sats
9988                         for _ in 0..dust_htlc_on_counterparty_tx {
9989                                 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
9990                         }
9991                 }
9992         }
9993
9994         let dust_overflow = dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx + 1);
9995         if exposure_breach_event == ExposureEvent::AtHTLCForward {
9996                 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 });
9997                 let mut config = UserConfig::default();
9998                 // With default dust exposure: 5000 sats
9999                 if on_holder_tx {
10000                         let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * (dust_outbound_htlc_on_holder_tx + 1);
10001                         let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * dust_inbound_htlc_on_holder_tx + dust_outbound_htlc_on_holder_tx_msat;
10002                         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)));
10003                 } else {
10004                         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)));
10005                 }
10006         } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
10007                 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 });
10008                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
10009                 check_added_monitors!(nodes[1], 1);
10010                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
10011                 assert_eq!(events.len(), 1);
10012                 let payment_event = SendEvent::from_event(events.remove(0));
10013                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
10014                 // With default dust exposure: 5000 sats
10015                 if on_holder_tx {
10016                         // Outbound dust balance: 6399 sats
10017                         let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
10018                         let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
10019                         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);
10020                 } else {
10021                         // Outbound dust balance: 5200 sats
10022                         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);
10023                 }
10024         } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
10025                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 2_500_000);
10026                 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at update_fee-swallowed HTLC", ); }
10027                 {
10028                         let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
10029                         *feerate_lock = *feerate_lock * 10;
10030                 }
10031                 nodes[0].node.timer_tick_occurred();
10032                 check_added_monitors!(nodes[0], 1);
10033                 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);
10034         }
10035
10036         let _ = nodes[0].node.get_and_clear_pending_msg_events();
10037         let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
10038         added_monitors.clear();
10039 }
10040
10041 #[test]
10042 fn test_max_dust_htlc_exposure() {
10043         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true);
10044         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true);
10045         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true);
10046         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false);
10047         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false);
10048         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false);
10049         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true);
10050         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false);
10051         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true);
10052         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false);
10053         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false);
10054         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true);
10055 }