d1dbad4720b814db3fb89476e0e8e8b7cee22193
[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         expect_payment_claimed!(nodes[0], payment_hash, 800_000);
1263         check_added_monitors!(nodes[0], 1);
1264
1265         // Broadcast node 1 commitment txn
1266         let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1267
1268         assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1269         let mut has_both_htlcs = 0; // check htlcs match ones committed
1270         for outp in remote_txn[0].output.iter() {
1271                 if outp.value == 800_000 / 1000 {
1272                         has_both_htlcs += 1;
1273                 } else if outp.value == 900_000 / 1000 {
1274                         has_both_htlcs += 1;
1275                 }
1276         }
1277         assert_eq!(has_both_htlcs, 2);
1278
1279         mine_transaction(&nodes[0], &remote_txn[0]);
1280         check_added_monitors!(nodes[0], 1);
1281         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
1282         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
1283
1284         let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1285         assert_eq!(claim_txn.len(), 8);
1286
1287         check_spends!(claim_txn[0], remote_txn[0]); // Immediate HTLC claim with preimage
1288
1289         check_spends!(claim_txn[1], chan_1.3); // Alternative commitment tx
1290         check_spends!(claim_txn[2], claim_txn[1]); // HTLC spend in alternative commitment tx
1291
1292         let bump_tx = if claim_txn[1] == claim_txn[4] {
1293                 assert_eq!(claim_txn[1], claim_txn[4]);
1294                 assert_eq!(claim_txn[2], claim_txn[5]);
1295
1296                 check_spends!(claim_txn[7], claim_txn[1]); // HTLC timeout on alternative commitment tx
1297
1298                 check_spends!(claim_txn[3], remote_txn[0]); // HTLC timeout on broadcasted commitment tx
1299                 &claim_txn[3]
1300         } else {
1301                 assert_eq!(claim_txn[1], claim_txn[3]);
1302                 assert_eq!(claim_txn[2], claim_txn[4]);
1303
1304                 check_spends!(claim_txn[5], claim_txn[1]); // HTLC timeout on alternative commitment tx
1305
1306                 check_spends!(claim_txn[7], remote_txn[0]); // HTLC timeout on broadcasted commitment tx
1307
1308                 &claim_txn[7]
1309         };
1310
1311         assert_eq!(claim_txn[0].input.len(), 1);
1312         assert_eq!(bump_tx.input.len(), 1);
1313         assert_eq!(claim_txn[0].input[0].previous_output, bump_tx.input[0].previous_output);
1314
1315         assert_eq!(claim_txn[0].input.len(), 1);
1316         assert_eq!(claim_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1317         assert_eq!(remote_txn[0].output[claim_txn[0].input[0].previous_output.vout as usize].value, 800);
1318
1319         assert_eq!(claim_txn[6].input.len(), 1);
1320         assert_eq!(claim_txn[6].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1321         check_spends!(claim_txn[6], remote_txn[0]);
1322         assert_eq!(remote_txn[0].output[claim_txn[6].input[0].previous_output.vout as usize].value, 900);
1323
1324         let events = nodes[0].node.get_and_clear_pending_msg_events();
1325         assert_eq!(events.len(), 3);
1326         for e in events {
1327                 match e {
1328                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1329                         MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1330                                 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1331                                 assert_eq!(msg.data, "Channel closed because commitment or closing transaction was confirmed on chain.");
1332                         },
1333                         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, .. } } => {
1334                                 assert!(update_add_htlcs.is_empty());
1335                                 assert!(update_fail_htlcs.is_empty());
1336                                 assert_eq!(update_fulfill_htlcs.len(), 1);
1337                                 assert!(update_fail_malformed_htlcs.is_empty());
1338                                 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1339                         },
1340                         _ => panic!("Unexpected event"),
1341                 }
1342         }
1343 }
1344
1345 #[test]
1346 fn test_basic_channel_reserve() {
1347         let chanmon_cfgs = create_chanmon_cfgs(2);
1348         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1349         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1350         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1351         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1352
1353         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1354         let channel_reserve = chan_stat.channel_reserve_msat;
1355
1356         // The 2* and +1 are for the fee spike reserve.
1357         let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], chan.2), 1 + 1, get_opt_anchors!(nodes[0], chan.2));
1358         let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1359         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send + 1);
1360         let err = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).err().unwrap();
1361         match err {
1362                 PaymentSendFailure::AllFailedRetrySafe(ref fails) => {
1363                         match &fails[0] {
1364                                 &APIError::ChannelUnavailable{ref err} =>
1365                                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1366                                 _ => panic!("Unexpected error variant"),
1367                         }
1368                 },
1369                 _ => panic!("Unexpected error variant"),
1370         }
1371         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1372         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);
1373
1374         send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1375 }
1376
1377 #[test]
1378 fn test_fee_spike_violation_fails_htlc() {
1379         let chanmon_cfgs = create_chanmon_cfgs(2);
1380         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1381         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1382         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1383         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1384
1385         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3460001);
1386         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1387         let secp_ctx = Secp256k1::new();
1388         let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1389
1390         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1391
1392         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1393         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &Some(payment_secret), cur_height, &None).unwrap();
1394         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1395         let msg = msgs::UpdateAddHTLC {
1396                 channel_id: chan.2,
1397                 htlc_id: 0,
1398                 amount_msat: htlc_msat,
1399                 payment_hash: payment_hash,
1400                 cltv_expiry: htlc_cltv,
1401                 onion_routing_packet: onion_packet,
1402         };
1403
1404         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1405
1406         // Now manually create the commitment_signed message corresponding to the update_add
1407         // nodes[0] just sent. In the code for construction of this message, "local" refers
1408         // to the sender of the message, and "remote" refers to the receiver.
1409
1410         let feerate_per_kw = get_feerate!(nodes[0], chan.2);
1411
1412         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1413
1414         // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1415         // needed to sign the new commitment tx and (2) sign the new commitment tx.
1416         let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1417                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
1418                 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
1419                 let chan_signer = local_chan.get_signer();
1420                 // Make the signer believe we validated another commitment, so we can release the secret
1421                 chan_signer.get_enforcement_state().last_holder_commitment -= 1;
1422
1423                 let pubkeys = chan_signer.pubkeys();
1424                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1425                  chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1426                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1427                  chan_signer.pubkeys().funding_pubkey)
1428         };
1429         let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1430                 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
1431                 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
1432                 let chan_signer = remote_chan.get_signer();
1433                 let pubkeys = chan_signer.pubkeys();
1434                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1435                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1436                  chan_signer.pubkeys().funding_pubkey)
1437         };
1438
1439         // Assemble the set of keys we can use for signatures for our commitment_signed message.
1440         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1441                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
1442
1443         // Build the remote commitment transaction so we can sign it, and then later use the
1444         // signature for the commitment_signed message.
1445         let local_chan_balance = 1313;
1446
1447         let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1448                 offered: false,
1449                 amount_msat: 3460001,
1450                 cltv_expiry: htlc_cltv,
1451                 payment_hash,
1452                 transaction_output_index: Some(1),
1453         };
1454
1455         let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1456
1457         let res = {
1458                 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
1459                 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
1460                 let local_chan_signer = local_chan.get_signer();
1461                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1462                         commitment_number,
1463                         95000,
1464                         local_chan_balance,
1465                         local_chan.opt_anchors(), local_funding, remote_funding,
1466                         commit_tx_keys.clone(),
1467                         feerate_per_kw,
1468                         &mut vec![(accepted_htlc_info, ())],
1469                         &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1470                 );
1471                 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
1472         };
1473
1474         let commit_signed_msg = msgs::CommitmentSigned {
1475                 channel_id: chan.2,
1476                 signature: res.0,
1477                 htlc_signatures: res.1
1478         };
1479
1480         // Send the commitment_signed message to the nodes[1].
1481         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1482         let _ = nodes[1].node.get_and_clear_pending_msg_events();
1483
1484         // Send the RAA to nodes[1].
1485         let raa_msg = msgs::RevokeAndACK {
1486                 channel_id: chan.2,
1487                 per_commitment_secret: local_secret,
1488                 next_per_commitment_point: next_local_point
1489         };
1490         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1491
1492         let events = nodes[1].node.get_and_clear_pending_msg_events();
1493         assert_eq!(events.len(), 1);
1494         // Make sure the HTLC failed in the way we expect.
1495         match events[0] {
1496                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1497                         assert_eq!(update_fail_htlcs.len(), 1);
1498                         update_fail_htlcs[0].clone()
1499                 },
1500                 _ => panic!("Unexpected event"),
1501         };
1502         nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1503                 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", ::hex::encode(raa_msg.channel_id)), 1);
1504
1505         check_added_monitors!(nodes[1], 2);
1506 }
1507
1508 #[test]
1509 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1510         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1511         // Set the fee rate for the channel very high, to the point where the fundee
1512         // sending any above-dust amount would result in a channel reserve violation.
1513         // In this test we check that we would be prevented from sending an HTLC in
1514         // this situation.
1515         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1516         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1517         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1518         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1519
1520         let opt_anchors = false;
1521
1522         let mut push_amt = 100_000_000;
1523         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1524         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1525
1526         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, InitFeatures::known(), InitFeatures::known());
1527
1528         // Sending exactly enough to hit the reserve amount should be accepted
1529         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1530                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1531         }
1532
1533         // However one more HTLC should be significantly over the reserve amount and fail.
1534         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1535         unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1536                 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1537         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1538         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);
1539 }
1540
1541 #[test]
1542 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1543         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1544         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1545         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1546         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1547         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1548
1549         let opt_anchors = false;
1550
1551         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1552         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1553         // transaction fee with 0 HTLCs (183 sats)).
1554         let mut push_amt = 100_000_000;
1555         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1556         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1557         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, InitFeatures::known(), InitFeatures::known());
1558
1559         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1560         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1561                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1562         }
1563
1564         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 700_000);
1565         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1566         let secp_ctx = Secp256k1::new();
1567         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1568         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1569         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1570         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 700_000, &Some(payment_secret), cur_height, &None).unwrap();
1571         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1572         let msg = msgs::UpdateAddHTLC {
1573                 channel_id: chan.2,
1574                 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1575                 amount_msat: htlc_msat,
1576                 payment_hash: payment_hash,
1577                 cltv_expiry: htlc_cltv,
1578                 onion_routing_packet: onion_packet,
1579         };
1580
1581         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1582         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1583         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);
1584         assert_eq!(nodes[0].node.list_channels().len(), 0);
1585         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1586         assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1587         check_added_monitors!(nodes[0], 1);
1588         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() });
1589 }
1590
1591 #[test]
1592 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1593         // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1594         // calculating our commitment transaction fee (this was previously broken).
1595         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1596         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1597
1598         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1599         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1600         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1601
1602         let opt_anchors = false;
1603
1604         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1605         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1606         // transaction fee with 0 HTLCs (183 sats)).
1607         let mut push_amt = 100_000_000;
1608         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1609         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1610         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt, InitFeatures::known(), InitFeatures::known());
1611
1612         let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1613                 + feerate_per_kw as u64 * htlc_success_tx_weight(opt_anchors) / 1000 * 1000 - 1;
1614         // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1615         // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1616         // commitment transaction fee.
1617         let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1618
1619         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1620         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1621                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1622         }
1623
1624         // One more than the dust amt should fail, however.
1625         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt + 1);
1626         unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1627                 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1628 }
1629
1630 #[test]
1631 fn test_chan_init_feerate_unaffordability() {
1632         // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to
1633         // channel reserve and feerate requirements.
1634         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1635         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1636         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1637         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1638         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1639
1640         let opt_anchors = false;
1641
1642         // Set the push_msat amount such that nodes[0] will not be able to afford to add even a single
1643         // HTLC.
1644         let mut push_amt = 100_000_000;
1645         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1646         assert_eq!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt + 1, 42, None).unwrap_err(),
1647                 APIError::APIMisuseError { err: "Funding amount (356) can't even pay fee for initial commitment transaction fee of 357.".to_string() });
1648
1649         // During open, we don't have a "counterparty channel reserve" to check against, so that
1650         // requirement only comes into play on the open_channel handling side.
1651         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1652         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt, 42, None).unwrap();
1653         let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
1654         open_channel_msg.push_msat += 1;
1655         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel_msg);
1656
1657         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1658         assert_eq!(msg_events.len(), 1);
1659         match msg_events[0] {
1660                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1661                         assert_eq!(msg.data, "Insufficient funding amount for initial reserve");
1662                 },
1663                 _ => panic!("Unexpected event"),
1664         }
1665 }
1666
1667 #[test]
1668 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1669         // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1670         // calculating our counterparty's commitment transaction fee (this was previously broken).
1671         let chanmon_cfgs = create_chanmon_cfgs(2);
1672         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1673         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1674         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1675         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000, InitFeatures::known(), InitFeatures::known());
1676
1677         let payment_amt = 46000; // Dust amount
1678         // In the previous code, these first four payments would succeed.
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         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1683
1684         // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
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         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1690
1691         // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1692         // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1693         // transaction fee and therefore perceived this next payment as a channel reserve violation.
1694         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1695 }
1696
1697 #[test]
1698 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1699         let chanmon_cfgs = create_chanmon_cfgs(3);
1700         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1701         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1702         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1703         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1704         let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1705
1706         let feemsat = 239;
1707         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1708         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1709         let feerate = get_feerate!(nodes[0], chan.2);
1710         let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
1711
1712         // Add a 2* and +1 for the fee spike reserve.
1713         let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1714         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;
1715         let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1716
1717         // Add a pending HTLC.
1718         let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1719         let payment_event_1 = {
1720                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1721                 check_added_monitors!(nodes[0], 1);
1722
1723                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1724                 assert_eq!(events.len(), 1);
1725                 SendEvent::from_event(events.remove(0))
1726         };
1727         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1728
1729         // Attempt to trigger a channel reserve violation --> payment failure.
1730         let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2, opt_anchors);
1731         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;
1732         let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1733         let (route_2, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_2);
1734
1735         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1736         let secp_ctx = Secp256k1::new();
1737         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1738         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1739         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1740         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height, &None).unwrap();
1741         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1742         let msg = msgs::UpdateAddHTLC {
1743                 channel_id: chan.2,
1744                 htlc_id: 1,
1745                 amount_msat: htlc_msat + 1,
1746                 payment_hash: our_payment_hash_1,
1747                 cltv_expiry: htlc_cltv,
1748                 onion_routing_packet: onion_packet,
1749         };
1750
1751         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1752         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1753         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1754         assert_eq!(nodes[1].node.list_channels().len(), 1);
1755         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1756         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1757         check_added_monitors!(nodes[1], 1);
1758         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() });
1759 }
1760
1761 #[test]
1762 fn test_inbound_outbound_capacity_is_not_zero() {
1763         let chanmon_cfgs = create_chanmon_cfgs(2);
1764         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1765         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1766         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1767         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1768         let channels0 = node_chanmgrs[0].list_channels();
1769         let channels1 = node_chanmgrs[1].list_channels();
1770         assert_eq!(channels0.len(), 1);
1771         assert_eq!(channels1.len(), 1);
1772
1773         let reserve = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100000);
1774         assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1775         assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1776
1777         assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1778         assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1779 }
1780
1781 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64, opt_anchors: bool) -> u64 {
1782         (commitment_tx_base_weight(opt_anchors) + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1783 }
1784
1785 #[test]
1786 fn test_channel_reserve_holding_cell_htlcs() {
1787         let chanmon_cfgs = create_chanmon_cfgs(3);
1788         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1789         // When this test was written, the default base fee floated based on the HTLC count.
1790         // It is now fixed, so we simply set the fee to the expected value here.
1791         let mut config = test_default_channel_config();
1792         config.channel_options.forwarding_fee_base_msat = 239;
1793         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1794         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1795         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1796         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1797
1798         let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1799         let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1800
1801         let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1802         let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1803
1804         macro_rules! expect_forward {
1805                 ($node: expr) => {{
1806                         let mut events = $node.node.get_and_clear_pending_msg_events();
1807                         assert_eq!(events.len(), 1);
1808                         check_added_monitors!($node, 1);
1809                         let payment_event = SendEvent::from_event(events.remove(0));
1810                         payment_event
1811                 }}
1812         }
1813
1814         let feemsat = 239; // set above
1815         let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1816         let feerate = get_feerate!(nodes[0], chan_1.2);
1817         let opt_anchors = get_opt_anchors!(nodes[0], chan_1.2);
1818
1819         let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1820
1821         // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1822         {
1823                 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_0);
1824                 route.paths[0].last_mut().unwrap().fee_msat += 1;
1825                 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1826                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1827                         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)));
1828                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1829                 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);
1830         }
1831
1832         // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1833         // nodes[0]'s wealth
1834         loop {
1835                 let amt_msat = recv_value_0 + total_fee_msat;
1836                 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1837                 // Also, ensure that each payment has enough to be over the dust limit to
1838                 // ensure it'll be included in each commit tx fee calculation.
1839                 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1840                 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1841                 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1842                         break;
1843                 }
1844                 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0);
1845
1846                 let (stat01_, stat11_, stat12_, stat22_) = (
1847                         get_channel_value_stat!(nodes[0], chan_1.2),
1848                         get_channel_value_stat!(nodes[1], chan_1.2),
1849                         get_channel_value_stat!(nodes[1], chan_2.2),
1850                         get_channel_value_stat!(nodes[2], chan_2.2),
1851                 );
1852
1853                 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1854                 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1855                 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1856                 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1857                 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1858         }
1859
1860         // adding pending output.
1861         // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1862         // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1863         // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1864         // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1865         // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1866         // cases where 1 msat over X amount will cause a payment failure, but anything less than
1867         // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1868         // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1869         // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1870         // policy.
1871         let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1872         let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1873         let amt_msat_1 = recv_value_1 + total_fee_msat;
1874
1875         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);
1876         let payment_event_1 = {
1877                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1878                 check_added_monitors!(nodes[0], 1);
1879
1880                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1881                 assert_eq!(events.len(), 1);
1882                 SendEvent::from_event(events.remove(0))
1883         };
1884         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1885
1886         // channel reserve test with htlc pending output > 0
1887         let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1888         {
1889                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_2 + 1);
1890                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1891                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1892                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1893         }
1894
1895         // split the rest to test holding cell
1896         let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1897         let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1898         let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1899         let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1900         {
1901                 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
1902                 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);
1903         }
1904
1905         // now see if they go through on both sides
1906         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);
1907         // but this will stuck in the holding cell
1908         nodes[0].node.send_payment(&route_21, our_payment_hash_21, &Some(our_payment_secret_21)).unwrap();
1909         check_added_monitors!(nodes[0], 0);
1910         let events = nodes[0].node.get_and_clear_pending_events();
1911         assert_eq!(events.len(), 0);
1912
1913         // test with outbound holding cell amount > 0
1914         {
1915                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22+1);
1916                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1917                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1918                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1919                 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);
1920         }
1921
1922         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);
1923         // this will also stuck in the holding cell
1924         nodes[0].node.send_payment(&route_22, our_payment_hash_22, &Some(our_payment_secret_22)).unwrap();
1925         check_added_monitors!(nodes[0], 0);
1926         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1927         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1928
1929         // flush the pending htlc
1930         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1931         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1932         check_added_monitors!(nodes[1], 1);
1933
1934         // the pending htlc should be promoted to committed
1935         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1936         check_added_monitors!(nodes[0], 1);
1937         let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1938
1939         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1940         let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1941         // No commitment_signed so get_event_msg's assert(len == 1) passes
1942         check_added_monitors!(nodes[0], 1);
1943
1944         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1945         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1946         check_added_monitors!(nodes[1], 1);
1947
1948         expect_pending_htlcs_forwardable!(nodes[1]);
1949
1950         let ref payment_event_11 = expect_forward!(nodes[1]);
1951         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1952         commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1953
1954         expect_pending_htlcs_forwardable!(nodes[2]);
1955         expect_payment_received!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
1956
1957         // flush the htlcs in the holding cell
1958         assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1959         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1960         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1961         commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1962         expect_pending_htlcs_forwardable!(nodes[1]);
1963
1964         let ref payment_event_3 = expect_forward!(nodes[1]);
1965         assert_eq!(payment_event_3.msgs.len(), 2);
1966         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1967         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1968
1969         commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1970         expect_pending_htlcs_forwardable!(nodes[2]);
1971
1972         let events = nodes[2].node.get_and_clear_pending_events();
1973         assert_eq!(events.len(), 2);
1974         match events[0] {
1975                 Event::PaymentReceived { ref payment_hash, ref purpose, amount_msat } => {
1976                         assert_eq!(our_payment_hash_21, *payment_hash);
1977                         assert_eq!(recv_value_21, amount_msat);
1978                         match &purpose {
1979                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1980                                         assert!(payment_preimage.is_none());
1981                                         assert_eq!(our_payment_secret_21, *payment_secret);
1982                                 },
1983                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
1984                         }
1985                 },
1986                 _ => panic!("Unexpected event"),
1987         }
1988         match events[1] {
1989                 Event::PaymentReceived { ref payment_hash, ref purpose, amount_msat } => {
1990                         assert_eq!(our_payment_hash_22, *payment_hash);
1991                         assert_eq!(recv_value_22, amount_msat);
1992                         match &purpose {
1993                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1994                                         assert!(payment_preimage.is_none());
1995                                         assert_eq!(our_payment_secret_22, *payment_secret);
1996                                 },
1997                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
1998                         }
1999                 },
2000                 _ => panic!("Unexpected event"),
2001         }
2002
2003         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
2004         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
2005         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
2006
2007         let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1, opt_anchors);
2008         let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2009         send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
2010
2011         let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
2012         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);
2013         let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
2014         assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2015         assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2016
2017         let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
2018         assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2019 }
2020
2021 #[test]
2022 fn channel_reserve_in_flight_removes() {
2023         // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2024         // can send to its counterparty, but due to update ordering, the other side may not yet have
2025         // considered those HTLCs fully removed.
2026         // This tests that we don't count HTLCs which will not be included in the next remote
2027         // commitment transaction towards the reserve value (as it implies no commitment transaction
2028         // will be generated which violates the remote reserve value).
2029         // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2030         // To test this we:
2031         //  * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2032         //    you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2033         //    you only consider the value of the first HTLC, it may not),
2034         //  * start routing a third HTLC from A to B,
2035         //  * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2036         //    the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2037         //  * deliver the first fulfill from B
2038         //  * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2039         //    claim,
2040         //  * deliver A's response CS and RAA.
2041         //    This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2042         //    removed it fully. B now has the push_msat plus the first two HTLCs in value.
2043         //  * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2044         //    of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2045         let chanmon_cfgs = create_chanmon_cfgs(2);
2046         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2047         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2048         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2049         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2050
2051         let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
2052         // Route the first two HTLCs.
2053         let payment_value_1 = b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000;
2054         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], payment_value_1);
2055         let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20_000);
2056
2057         // Start routing the third HTLC (this is just used to get everyone in the right state).
2058         let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
2059         let send_1 = {
2060                 nodes[0].node.send_payment(&route, payment_hash_3, &Some(payment_secret_3)).unwrap();
2061                 check_added_monitors!(nodes[0], 1);
2062                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2063                 assert_eq!(events.len(), 1);
2064                 SendEvent::from_event(events.remove(0))
2065         };
2066
2067         // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2068         // initial fulfill/CS.
2069         nodes[1].node.claim_funds(payment_preimage_1);
2070         expect_payment_claimed!(nodes[1], payment_hash_1, payment_value_1);
2071         check_added_monitors!(nodes[1], 1);
2072         let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2073
2074         // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2075         // remove the second HTLC when we send the HTLC back from B to A.
2076         nodes[1].node.claim_funds(payment_preimage_2);
2077         expect_payment_claimed!(nodes[1], payment_hash_2, 20_000);
2078         check_added_monitors!(nodes[1], 1);
2079         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2080
2081         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2082         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2083         check_added_monitors!(nodes[0], 1);
2084         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2085         expect_payment_sent_without_paths!(nodes[0], payment_preimage_1);
2086
2087         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2088         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2089         check_added_monitors!(nodes[1], 1);
2090         // B is already AwaitingRAA, so cant generate a CS here
2091         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2092
2093         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2094         check_added_monitors!(nodes[1], 1);
2095         let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2096
2097         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2098         check_added_monitors!(nodes[0], 1);
2099         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2100
2101         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2102         check_added_monitors!(nodes[1], 1);
2103         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2104
2105         // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2106         // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2107         // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2108         // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2109         // on-chain as necessary).
2110         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2111         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2112         check_added_monitors!(nodes[0], 1);
2113         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2114         expect_payment_sent_without_paths!(nodes[0], payment_preimage_2);
2115
2116         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2117         check_added_monitors!(nodes[1], 1);
2118         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2119
2120         expect_pending_htlcs_forwardable!(nodes[1]);
2121         expect_payment_received!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2122
2123         // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2124         // resolve the second HTLC from A's point of view.
2125         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2126         check_added_monitors!(nodes[0], 1);
2127         expect_payment_path_successful!(nodes[0]);
2128         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2129
2130         // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2131         // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2132         let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2133         let send_2 = {
2134                 nodes[1].node.send_payment(&route, payment_hash_4, &Some(payment_secret_4)).unwrap();
2135                 check_added_monitors!(nodes[1], 1);
2136                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2137                 assert_eq!(events.len(), 1);
2138                 SendEvent::from_event(events.remove(0))
2139         };
2140
2141         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2142         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2143         check_added_monitors!(nodes[0], 1);
2144         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2145
2146         // Now just resolve all the outstanding messages/HTLCs for completeness...
2147
2148         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2149         check_added_monitors!(nodes[1], 1);
2150         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2151
2152         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2153         check_added_monitors!(nodes[1], 1);
2154
2155         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2156         check_added_monitors!(nodes[0], 1);
2157         expect_payment_path_successful!(nodes[0]);
2158         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2159
2160         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2161         check_added_monitors!(nodes[1], 1);
2162         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2163
2164         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2165         check_added_monitors!(nodes[0], 1);
2166
2167         expect_pending_htlcs_forwardable!(nodes[0]);
2168         expect_payment_received!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2169
2170         claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2171         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2172 }
2173
2174 #[test]
2175 fn channel_monitor_network_test() {
2176         // Simple test which builds a network of ChannelManagers, connects them to each other, and
2177         // tests that ChannelMonitor is able to recover from various states.
2178         let chanmon_cfgs = create_chanmon_cfgs(5);
2179         let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2180         let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2181         let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2182
2183         // Create some initial channels
2184         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2185         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2186         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
2187         let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
2188
2189         // Make sure all nodes are at the same starting height
2190         connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2191         connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2192         connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2193         connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2194         connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2195
2196         // Rebalance the network a bit by relaying one payment through all the channels...
2197         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2198         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2199         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2200         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2201
2202         // Simple case with no pending HTLCs:
2203         nodes[1].node.force_close_channel(&chan_1.2, &nodes[0].node.get_our_node_id()).unwrap();
2204         check_added_monitors!(nodes[1], 1);
2205         check_closed_broadcast!(nodes[1], true);
2206         {
2207                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2208                 assert_eq!(node_txn.len(), 1);
2209                 mine_transaction(&nodes[0], &node_txn[0]);
2210                 check_added_monitors!(nodes[0], 1);
2211                 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
2212         }
2213         check_closed_broadcast!(nodes[0], true);
2214         assert_eq!(nodes[0].node.list_channels().len(), 0);
2215         assert_eq!(nodes[1].node.list_channels().len(), 1);
2216         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2217         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2218
2219         // One pending HTLC is discarded by the force-close:
2220         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[1], &[&nodes[2], &nodes[3]], 3_000_000);
2221
2222         // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2223         // broadcasted until we reach the timelock time).
2224         nodes[1].node.force_close_channel(&chan_2.2, &nodes[2].node.get_our_node_id()).unwrap();
2225         check_closed_broadcast!(nodes[1], true);
2226         check_added_monitors!(nodes[1], 1);
2227         {
2228                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2229                 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2230                 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2231                 mine_transaction(&nodes[2], &node_txn[0]);
2232                 check_added_monitors!(nodes[2], 1);
2233                 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
2234         }
2235         check_closed_broadcast!(nodes[2], true);
2236         assert_eq!(nodes[1].node.list_channels().len(), 0);
2237         assert_eq!(nodes[2].node.list_channels().len(), 1);
2238         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2239         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2240
2241         macro_rules! claim_funds {
2242                 ($node: expr, $prev_node: expr, $preimage: expr, $payment_hash: expr) => {
2243                         {
2244                                 $node.node.claim_funds($preimage);
2245                                 expect_payment_claimed!($node, $payment_hash, 3_000_000);
2246                                 check_added_monitors!($node, 1);
2247
2248                                 let events = $node.node.get_and_clear_pending_msg_events();
2249                                 assert_eq!(events.len(), 1);
2250                                 match events[0] {
2251                                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2252                                                 assert!(update_add_htlcs.is_empty());
2253                                                 assert!(update_fail_htlcs.is_empty());
2254                                                 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2255                                         },
2256                                         _ => panic!("Unexpected event"),
2257                                 };
2258                         }
2259                 }
2260         }
2261
2262         // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2263         // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2264         nodes[2].node.force_close_channel(&chan_3.2, &nodes[3].node.get_our_node_id()).unwrap();
2265         check_added_monitors!(nodes[2], 1);
2266         check_closed_broadcast!(nodes[2], true);
2267         let node2_commitment_txid;
2268         {
2269                 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2270                 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2271                 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2272                 node2_commitment_txid = node_txn[0].txid();
2273
2274                 // Claim the payment on nodes[3], giving it knowledge of the preimage
2275                 claim_funds!(nodes[3], nodes[2], payment_preimage_1, payment_hash_1);
2276                 mine_transaction(&nodes[3], &node_txn[0]);
2277                 check_added_monitors!(nodes[3], 1);
2278                 check_preimage_claim(&nodes[3], &node_txn);
2279         }
2280         check_closed_broadcast!(nodes[3], true);
2281         assert_eq!(nodes[2].node.list_channels().len(), 0);
2282         assert_eq!(nodes[3].node.list_channels().len(), 1);
2283         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
2284         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2285
2286         // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2287         // confusing us in the following tests.
2288         let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2289
2290         // One pending HTLC to time out:
2291         let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[3], &[&nodes[4]], 3_000_000);
2292         // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2293         // buffer space).
2294
2295         let (close_chan_update_1, close_chan_update_2) = {
2296                 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2297                 let events = nodes[3].node.get_and_clear_pending_msg_events();
2298                 assert_eq!(events.len(), 2);
2299                 let close_chan_update_1 = match events[0] {
2300                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2301                                 msg.clone()
2302                         },
2303                         _ => panic!("Unexpected event"),
2304                 };
2305                 match events[1] {
2306                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2307                                 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2308                         },
2309                         _ => panic!("Unexpected event"),
2310                 }
2311                 check_added_monitors!(nodes[3], 1);
2312
2313                 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2314                 {
2315                         let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2316                         node_txn.retain(|tx| {
2317                                 if tx.input[0].previous_output.txid == node2_commitment_txid {
2318                                         false
2319                                 } else { true }
2320                         });
2321                 }
2322
2323                 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2324
2325                 // Claim the payment on nodes[4], giving it knowledge of the preimage
2326                 claim_funds!(nodes[4], nodes[3], payment_preimage_2, payment_hash_2);
2327
2328                 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2329                 let events = nodes[4].node.get_and_clear_pending_msg_events();
2330                 assert_eq!(events.len(), 2);
2331                 let close_chan_update_2 = match events[0] {
2332                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2333                                 msg.clone()
2334                         },
2335                         _ => panic!("Unexpected event"),
2336                 };
2337                 match events[1] {
2338                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2339                                 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2340                         },
2341                         _ => panic!("Unexpected event"),
2342                 }
2343                 check_added_monitors!(nodes[4], 1);
2344                 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2345
2346                 mine_transaction(&nodes[4], &node_txn[0]);
2347                 check_preimage_claim(&nodes[4], &node_txn);
2348                 (close_chan_update_1, close_chan_update_2)
2349         };
2350         nodes[3].net_graph_msg_handler.handle_channel_update(&close_chan_update_2).unwrap();
2351         nodes[4].net_graph_msg_handler.handle_channel_update(&close_chan_update_1).unwrap();
2352         assert_eq!(nodes[3].node.list_channels().len(), 0);
2353         assert_eq!(nodes[4].node.list_channels().len(), 0);
2354
2355         nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon).unwrap();
2356         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2357         check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed);
2358 }
2359
2360 #[test]
2361 fn test_justice_tx() {
2362         // Test justice txn built on revoked HTLC-Success tx, against both sides
2363         let mut alice_config = UserConfig::default();
2364         alice_config.channel_options.announced_channel = true;
2365         alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
2366         alice_config.own_channel_config.our_to_self_delay = 6 * 24 * 5;
2367         let mut bob_config = UserConfig::default();
2368         bob_config.channel_options.announced_channel = true;
2369         bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
2370         bob_config.own_channel_config.our_to_self_delay = 6 * 24 * 3;
2371         let user_cfgs = [Some(alice_config), Some(bob_config)];
2372         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2373         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2374         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2375         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2376         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2377         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2378         *nodes[0].connect_style.borrow_mut() = ConnectStyle::FullBlockViaListen;
2379         // Create some new channels:
2380         let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2381
2382         // A pending HTLC which will be revoked:
2383         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2384         // Get the will-be-revoked local txn from nodes[0]
2385         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2386         assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2387         assert_eq!(revoked_local_txn[0].input.len(), 1);
2388         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2389         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2390         assert_eq!(revoked_local_txn[1].input.len(), 1);
2391         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2392         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2393         // Revoke the old state
2394         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2395
2396         {
2397                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2398                 {
2399                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2400                         assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2401                         assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2402
2403                         check_spends!(node_txn[0], revoked_local_txn[0]);
2404                         node_txn.swap_remove(0);
2405                         node_txn.truncate(1);
2406                 }
2407                 check_added_monitors!(nodes[1], 1);
2408                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2409                 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2410
2411                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2412                 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2413                 // Verify broadcast of revoked HTLC-timeout
2414                 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2415                 check_added_monitors!(nodes[0], 1);
2416                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2417                 // Broadcast revoked HTLC-timeout on node 1
2418                 mine_transaction(&nodes[1], &node_txn[1]);
2419                 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2420         }
2421         get_announce_close_broadcast_events(&nodes, 0, 1);
2422
2423         assert_eq!(nodes[0].node.list_channels().len(), 0);
2424         assert_eq!(nodes[1].node.list_channels().len(), 0);
2425
2426         // We test justice_tx build by A on B's revoked HTLC-Success tx
2427         // Create some new channels:
2428         let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2429         {
2430                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2431                 node_txn.clear();
2432         }
2433
2434         // A pending HTLC which will be revoked:
2435         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2436         // Get the will-be-revoked local txn from B
2437         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2438         assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2439         assert_eq!(revoked_local_txn[0].input.len(), 1);
2440         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2441         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2442         // Revoke the old state
2443         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2444         {
2445                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2446                 {
2447                         let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2448                         assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2449                         assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2450
2451                         check_spends!(node_txn[0], revoked_local_txn[0]);
2452                         node_txn.swap_remove(0);
2453                 }
2454                 check_added_monitors!(nodes[0], 1);
2455                 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2456
2457                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2458                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2459                 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2460                 check_added_monitors!(nodes[1], 1);
2461                 mine_transaction(&nodes[0], &node_txn[1]);
2462                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2463                 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2464         }
2465         get_announce_close_broadcast_events(&nodes, 0, 1);
2466         assert_eq!(nodes[0].node.list_channels().len(), 0);
2467         assert_eq!(nodes[1].node.list_channels().len(), 0);
2468 }
2469
2470 #[test]
2471 fn revoked_output_claim() {
2472         // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2473         // transaction is broadcast by its counterparty
2474         let chanmon_cfgs = create_chanmon_cfgs(2);
2475         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2476         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2477         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2478         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2479         // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2480         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2481         assert_eq!(revoked_local_txn.len(), 1);
2482         // Only output is the full channel value back to nodes[0]:
2483         assert_eq!(revoked_local_txn[0].output.len(), 1);
2484         // Send a payment through, updating everyone's latest commitment txn
2485         send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2486
2487         // Inform nodes[1] that nodes[0] broadcast a stale tx
2488         mine_transaction(&nodes[1], &revoked_local_txn[0]);
2489         check_added_monitors!(nodes[1], 1);
2490         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2491         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2492         assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2493
2494         check_spends!(node_txn[0], revoked_local_txn[0]);
2495         check_spends!(node_txn[1], chan_1.3);
2496
2497         // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2498         mine_transaction(&nodes[0], &revoked_local_txn[0]);
2499         get_announce_close_broadcast_events(&nodes, 0, 1);
2500         check_added_monitors!(nodes[0], 1);
2501         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2502 }
2503
2504 #[test]
2505 fn claim_htlc_outputs_shared_tx() {
2506         // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2507         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2508         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2509         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2510         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2511         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2512
2513         // Create some new channel:
2514         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2515
2516         // Rebalance the network to generate htlc in the two directions
2517         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
2518         // 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
2519         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2520         let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2521
2522         // Get the will-be-revoked local txn from node[0]
2523         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2524         assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2525         assert_eq!(revoked_local_txn[0].input.len(), 1);
2526         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2527         assert_eq!(revoked_local_txn[1].input.len(), 1);
2528         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2529         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2530         check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2531
2532         //Revoke the old state
2533         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2534
2535         {
2536                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2537                 check_added_monitors!(nodes[0], 1);
2538                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2539                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2540                 check_added_monitors!(nodes[1], 1);
2541                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2542                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2543                 expect_payment_failed!(nodes[1], payment_hash_2, true);
2544
2545                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2546                 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment
2547
2548                 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2549                 check_spends!(node_txn[0], revoked_local_txn[0]);
2550
2551                 let mut witness_lens = BTreeSet::new();
2552                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2553                 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2554                 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2555                 assert_eq!(witness_lens.len(), 3);
2556                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2557                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2558                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2559
2560                 // Next nodes[1] broadcasts its current local tx state:
2561                 assert_eq!(node_txn[1].input.len(), 1);
2562                 assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
2563         }
2564         get_announce_close_broadcast_events(&nodes, 0, 1);
2565         assert_eq!(nodes[0].node.list_channels().len(), 0);
2566         assert_eq!(nodes[1].node.list_channels().len(), 0);
2567 }
2568
2569 #[test]
2570 fn claim_htlc_outputs_single_tx() {
2571         // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2572         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2573         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2574         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2575         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2576         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2577
2578         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2579
2580         // Rebalance the network to generate htlc in the two directions
2581         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
2582         // 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
2583         // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2584         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2585         let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2586
2587         // Get the will-be-revoked local txn from node[0]
2588         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2589
2590         //Revoke the old state
2591         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2592
2593         {
2594                 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2595                 check_added_monitors!(nodes[0], 1);
2596                 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2597                 check_added_monitors!(nodes[1], 1);
2598                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2599                 let mut events = nodes[0].node.get_and_clear_pending_events();
2600                 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2601                 match events[1] {
2602                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2603                         _ => panic!("Unexpected event"),
2604                 }
2605
2606                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2607                 expect_payment_failed!(nodes[1], payment_hash_2, true);
2608
2609                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2610                 assert!(node_txn.len() == 9 || node_txn.len() == 10);
2611
2612                 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2613                 assert_eq!(node_txn[0].input.len(), 1);
2614                 check_spends!(node_txn[0], chan_1.3);
2615                 assert_eq!(node_txn[1].input.len(), 1);
2616                 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2617                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2618                 check_spends!(node_txn[1], node_txn[0]);
2619
2620                 // Justice transactions are indices 1-2-4
2621                 assert_eq!(node_txn[2].input.len(), 1);
2622                 assert_eq!(node_txn[3].input.len(), 1);
2623                 assert_eq!(node_txn[4].input.len(), 1);
2624
2625                 check_spends!(node_txn[2], revoked_local_txn[0]);
2626                 check_spends!(node_txn[3], revoked_local_txn[0]);
2627                 check_spends!(node_txn[4], revoked_local_txn[0]);
2628
2629                 let mut witness_lens = BTreeSet::new();
2630                 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2631                 witness_lens.insert(node_txn[3].input[0].witness.last().unwrap().len());
2632                 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2633                 assert_eq!(witness_lens.len(), 3);
2634                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2635                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2636                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2637         }
2638         get_announce_close_broadcast_events(&nodes, 0, 1);
2639         assert_eq!(nodes[0].node.list_channels().len(), 0);
2640         assert_eq!(nodes[1].node.list_channels().len(), 0);
2641 }
2642
2643 #[test]
2644 fn test_htlc_on_chain_success() {
2645         // Test that in case of a unilateral close onchain, we detect the state of output and pass
2646         // the preimage backward accordingly. So here we test that ChannelManager is
2647         // broadcasting the right event to other nodes in payment path.
2648         // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2649         // A --------------------> B ----------------------> C (preimage)
2650         // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2651         // commitment transaction was broadcast.
2652         // Then, B should learn the preimage from said transactions, attempting to claim backwards
2653         // towards B.
2654         // B should be able to claim via preimage if A then broadcasts its local tx.
2655         // Finally, when A sees B's latest local commitment transaction it should be able to claim
2656         // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2657         // PaymentSent event).
2658
2659         let chanmon_cfgs = create_chanmon_cfgs(3);
2660         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2661         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2662         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2663
2664         // Create some initial channels
2665         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2666         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2667
2668         // Ensure all nodes are at the same height
2669         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2670         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2671         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2672         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2673
2674         // Rebalance the network a bit by relaying one payment through all the channels...
2675         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2676         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2677
2678         let (our_payment_preimage, payment_hash_1, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2679         let (our_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2680
2681         // Broadcast legit commitment tx from C on B's chain
2682         // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2683         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2684         assert_eq!(commitment_tx.len(), 1);
2685         check_spends!(commitment_tx[0], chan_2.3);
2686         nodes[2].node.claim_funds(our_payment_preimage);
2687         expect_payment_claimed!(nodes[2], payment_hash_1, 3_000_000);
2688         nodes[2].node.claim_funds(our_payment_preimage_2);
2689         expect_payment_claimed!(nodes[2], payment_hash_2, 3_000_000);
2690         check_added_monitors!(nodes[2], 2);
2691         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2692         assert!(updates.update_add_htlcs.is_empty());
2693         assert!(updates.update_fail_htlcs.is_empty());
2694         assert!(updates.update_fail_malformed_htlcs.is_empty());
2695         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2696
2697         mine_transaction(&nodes[2], &commitment_tx[0]);
2698         check_closed_broadcast!(nodes[2], true);
2699         check_added_monitors!(nodes[2], 1);
2700         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2701         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)
2702         assert_eq!(node_txn.len(), 5);
2703         assert_eq!(node_txn[0], node_txn[3]);
2704         assert_eq!(node_txn[1], node_txn[4]);
2705         assert_eq!(node_txn[2], commitment_tx[0]);
2706         check_spends!(node_txn[0], commitment_tx[0]);
2707         check_spends!(node_txn[1], commitment_tx[0]);
2708         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2709         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2710         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2711         assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2712         assert_eq!(node_txn[0].lock_time, 0);
2713         assert_eq!(node_txn[1].lock_time, 0);
2714
2715         // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2716         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2717         connect_block(&nodes[1], &Block { header, txdata: node_txn});
2718         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2719         {
2720                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2721                 assert_eq!(added_monitors.len(), 1);
2722                 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2723                 added_monitors.clear();
2724         }
2725         let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2726         assert_eq!(forwarded_events.len(), 3);
2727         match forwarded_events[0] {
2728                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2729                 _ => panic!("Unexpected event"),
2730         }
2731         let chan_id = Some(chan_1.2);
2732         match forwarded_events[1] {
2733                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
2734                         assert_eq!(fee_earned_msat, Some(1000));
2735                         assert_eq!(prev_channel_id, chan_id);
2736                         assert_eq!(claim_from_onchain_tx, true);
2737                         assert_eq!(next_channel_id, Some(chan_2.2));
2738                 },
2739                 _ => panic!()
2740         }
2741         match forwarded_events[2] {
2742                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
2743                         assert_eq!(fee_earned_msat, Some(1000));
2744                         assert_eq!(prev_channel_id, chan_id);
2745                         assert_eq!(claim_from_onchain_tx, true);
2746                         assert_eq!(next_channel_id, Some(chan_2.2));
2747                 },
2748                 _ => panic!()
2749         }
2750         let events = nodes[1].node.get_and_clear_pending_msg_events();
2751         {
2752                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2753                 assert_eq!(added_monitors.len(), 2);
2754                 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2755                 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2756                 added_monitors.clear();
2757         }
2758         assert_eq!(events.len(), 3);
2759         match events[0] {
2760                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2761                 _ => panic!("Unexpected event"),
2762         }
2763         match events[1] {
2764                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2765                 _ => panic!("Unexpected event"),
2766         }
2767
2768         match events[2] {
2769                 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, .. } } => {
2770                         assert!(update_add_htlcs.is_empty());
2771                         assert!(update_fail_htlcs.is_empty());
2772                         assert_eq!(update_fulfill_htlcs.len(), 1);
2773                         assert!(update_fail_malformed_htlcs.is_empty());
2774                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2775                 },
2776                 _ => panic!("Unexpected event"),
2777         };
2778         macro_rules! check_tx_local_broadcast {
2779                 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2780                         let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2781                         assert_eq!(node_txn.len(), 3);
2782                         // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2783                         // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2784                         check_spends!(node_txn[1], $commitment_tx);
2785                         check_spends!(node_txn[2], $commitment_tx);
2786                         assert_ne!(node_txn[1].lock_time, 0);
2787                         assert_ne!(node_txn[2].lock_time, 0);
2788                         if $htlc_offered {
2789                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2790                                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2791                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2792                                 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2793                         } else {
2794                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2795                                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2796                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2797                                 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2798                         }
2799                         check_spends!(node_txn[0], $chan_tx);
2800                         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2801                         node_txn.clear();
2802                 } }
2803         }
2804         // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2805         // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2806         // timeout-claim of the output that nodes[2] just claimed via success.
2807         check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2808
2809         // Broadcast legit commitment tx from A on B's chain
2810         // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
2811         let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2812         check_spends!(node_a_commitment_tx[0], chan_1.3);
2813         mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2814         check_closed_broadcast!(nodes[1], true);
2815         check_added_monitors!(nodes[1], 1);
2816         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2817         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2818         assert_eq!(node_txn.len(), 6); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 3 (HTLC-Success, 2* RBF bumps of above HTLC txn)
2819         let commitment_spend =
2820                 if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2821                         check_spends!(node_txn[1], commitment_tx[0]);
2822                         check_spends!(node_txn[2], commitment_tx[0]);
2823                         assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2824                         &node_txn[0]
2825                 } else {
2826                         check_spends!(node_txn[0], commitment_tx[0]);
2827                         check_spends!(node_txn[1], commitment_tx[0]);
2828                         assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2829                         &node_txn[2]
2830                 };
2831
2832         check_spends!(commitment_spend, node_a_commitment_tx[0]);
2833         assert_eq!(commitment_spend.input.len(), 2);
2834         assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2835         assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2836         assert_eq!(commitment_spend.lock_time, 0);
2837         assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2838         check_spends!(node_txn[3], chan_1.3);
2839         assert_eq!(node_txn[3].input[0].witness.clone().last().unwrap().len(), 71);
2840         check_spends!(node_txn[4], node_txn[3]);
2841         check_spends!(node_txn[5], node_txn[3]);
2842         // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2843         // we already checked the same situation with A.
2844
2845         // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2846         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2847         connect_block(&nodes[0], &Block { header, txdata: vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()] });
2848         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2849         check_closed_broadcast!(nodes[0], true);
2850         check_added_monitors!(nodes[0], 1);
2851         let events = nodes[0].node.get_and_clear_pending_events();
2852         assert_eq!(events.len(), 5);
2853         let mut first_claimed = false;
2854         for event in events {
2855                 match event {
2856                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
2857                                 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
2858                                         assert!(!first_claimed);
2859                                         first_claimed = true;
2860                                 } else {
2861                                         assert_eq!(payment_preimage, our_payment_preimage_2);
2862                                         assert_eq!(payment_hash, payment_hash_2);
2863                                 }
2864                         },
2865                         Event::PaymentPathSuccessful { .. } => {},
2866                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
2867                         _ => panic!("Unexpected event"),
2868                 }
2869         }
2870         check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0], chan_1.3);
2871 }
2872
2873 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2874         // Test that in case of a unilateral close onchain, we detect the state of output and
2875         // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2876         // broadcasting the right event to other nodes in payment path.
2877         // A ------------------> B ----------------------> C (timeout)
2878         //    B's commitment tx                 C's commitment tx
2879         //            \                                  \
2880         //         B's HTLC timeout tx               B's timeout tx
2881
2882         let chanmon_cfgs = create_chanmon_cfgs(3);
2883         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2884         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2885         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2886         *nodes[0].connect_style.borrow_mut() = connect_style;
2887         *nodes[1].connect_style.borrow_mut() = connect_style;
2888         *nodes[2].connect_style.borrow_mut() = connect_style;
2889
2890         // Create some intial channels
2891         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2892         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2893
2894         // Rebalance the network a bit by relaying one payment thorugh all the channels...
2895         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2896         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2897
2898         let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2899
2900         // Broadcast legit commitment tx from C on B's chain
2901         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2902         check_spends!(commitment_tx[0], chan_2.3);
2903         nodes[2].node.fail_htlc_backwards(&payment_hash);
2904         check_added_monitors!(nodes[2], 0);
2905         expect_pending_htlcs_forwardable!(nodes[2]);
2906         check_added_monitors!(nodes[2], 1);
2907
2908         let events = nodes[2].node.get_and_clear_pending_msg_events();
2909         assert_eq!(events.len(), 1);
2910         match events[0] {
2911                 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, .. } } => {
2912                         assert!(update_add_htlcs.is_empty());
2913                         assert!(!update_fail_htlcs.is_empty());
2914                         assert!(update_fulfill_htlcs.is_empty());
2915                         assert!(update_fail_malformed_htlcs.is_empty());
2916                         assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2917                 },
2918                 _ => panic!("Unexpected event"),
2919         };
2920         mine_transaction(&nodes[2], &commitment_tx[0]);
2921         check_closed_broadcast!(nodes[2], true);
2922         check_added_monitors!(nodes[2], 1);
2923         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2924         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2925         assert_eq!(node_txn.len(), 1);
2926         check_spends!(node_txn[0], chan_2.3);
2927         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2928
2929         // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2930         // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2931         connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2932         mine_transaction(&nodes[1], &commitment_tx[0]);
2933         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2934         let timeout_tx;
2935         {
2936                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2937                 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
2938                 assert_eq!(node_txn[0], node_txn[3]);
2939                 assert_eq!(node_txn[1], node_txn[4]);
2940
2941                 check_spends!(node_txn[2], commitment_tx[0]);
2942                 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2943
2944                 check_spends!(node_txn[0], chan_2.3);
2945                 check_spends!(node_txn[1], node_txn[0]);
2946                 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2947                 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2948
2949                 timeout_tx = node_txn[2].clone();
2950                 node_txn.clear();
2951         }
2952
2953         mine_transaction(&nodes[1], &timeout_tx);
2954         check_added_monitors!(nodes[1], 1);
2955         check_closed_broadcast!(nodes[1], true);
2956         {
2957                 // B will rebroadcast a fee-bumped timeout transaction here.
2958                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2959                 assert_eq!(node_txn.len(), 1);
2960                 check_spends!(node_txn[0], commitment_tx[0]);
2961         }
2962
2963         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2964         {
2965                 // B may rebroadcast its own holder commitment transaction here, as a safeguard against
2966                 // some incredibly unlikely partial-eclipse-attack scenarios. That said, because the
2967                 // original commitment_tx[0] (also spending chan_2.3) has reached ANTI_REORG_DELAY B really
2968                 // shouldn't broadcast anything here, and in some connect style scenarios we do not.
2969                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2970                 if node_txn.len() == 1 {
2971                         check_spends!(node_txn[0], chan_2.3);
2972                 } else {
2973                         assert_eq!(node_txn.len(), 0);
2974                 }
2975         }
2976
2977         expect_pending_htlcs_forwardable!(nodes[1]);
2978         check_added_monitors!(nodes[1], 1);
2979         let events = nodes[1].node.get_and_clear_pending_msg_events();
2980         assert_eq!(events.len(), 1);
2981         match events[0] {
2982                 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, .. } } => {
2983                         assert!(update_add_htlcs.is_empty());
2984                         assert!(!update_fail_htlcs.is_empty());
2985                         assert!(update_fulfill_htlcs.is_empty());
2986                         assert!(update_fail_malformed_htlcs.is_empty());
2987                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2988                 },
2989                 _ => panic!("Unexpected event"),
2990         };
2991
2992         // Broadcast legit commitment tx from B on A's chain
2993         let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
2994         check_spends!(commitment_tx[0], chan_1.3);
2995
2996         mine_transaction(&nodes[0], &commitment_tx[0]);
2997         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2998
2999         check_closed_broadcast!(nodes[0], true);
3000         check_added_monitors!(nodes[0], 1);
3001         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
3002         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 commitment tx, ChannelMonitor : 1 timeout tx
3003         assert_eq!(node_txn.len(), 2);
3004         check_spends!(node_txn[0], chan_1.3);
3005         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
3006         check_spends!(node_txn[1], commitment_tx[0]);
3007         assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3008 }
3009
3010 #[test]
3011 fn test_htlc_on_chain_timeout() {
3012         do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
3013         do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
3014         do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
3015 }
3016
3017 #[test]
3018 fn test_simple_commitment_revoked_fail_backward() {
3019         // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3020         // and fail backward accordingly.
3021
3022         let chanmon_cfgs = create_chanmon_cfgs(3);
3023         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3024         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3025         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3026
3027         // Create some initial channels
3028         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3029         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3030
3031         let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3032         // Get the will-be-revoked local txn from nodes[2]
3033         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3034         // Revoke the old state
3035         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3036
3037         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3038
3039         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3040         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3041         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3042         check_added_monitors!(nodes[1], 1);
3043         check_closed_broadcast!(nodes[1], true);
3044
3045         expect_pending_htlcs_forwardable!(nodes[1]);
3046         check_added_monitors!(nodes[1], 1);
3047         let events = nodes[1].node.get_and_clear_pending_msg_events();
3048         assert_eq!(events.len(), 1);
3049         match events[0] {
3050                 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, .. } } => {
3051                         assert!(update_add_htlcs.is_empty());
3052                         assert_eq!(update_fail_htlcs.len(), 1);
3053                         assert!(update_fulfill_htlcs.is_empty());
3054                         assert!(update_fail_malformed_htlcs.is_empty());
3055                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3056
3057                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3058                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3059                         expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3060                 },
3061                 _ => panic!("Unexpected event"),
3062         }
3063 }
3064
3065 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3066         // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3067         // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3068         // commitment transaction anymore.
3069         // To do this, we have the peer which will broadcast a revoked commitment transaction send
3070         // a number of update_fail/commitment_signed updates without ever sending the RAA in
3071         // response to our commitment_signed. This is somewhat misbehavior-y, though not
3072         // technically disallowed and we should probably handle it reasonably.
3073         // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3074         // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3075         // transactions:
3076         // * Once we move it out of our holding cell/add it, we will immediately include it in a
3077         //   commitment_signed (implying it will be in the latest remote commitment transaction).
3078         // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3079         //   and once they revoke the previous commitment transaction (allowing us to send a new
3080         //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3081         let chanmon_cfgs = create_chanmon_cfgs(3);
3082         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3083         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3084         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3085
3086         // Create some initial channels
3087         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3088         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3089
3090         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 });
3091         // Get the will-be-revoked local txn from nodes[2]
3092         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3093         assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3094         // Revoke the old state
3095         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3096
3097         let value = if use_dust {
3098                 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3099                 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3100                 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3101         } else { 3000000 };
3102
3103         let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3104         let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3105         let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3106
3107         nodes[2].node.fail_htlc_backwards(&first_payment_hash);
3108         expect_pending_htlcs_forwardable!(nodes[2]);
3109         check_added_monitors!(nodes[2], 1);
3110         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3111         assert!(updates.update_add_htlcs.is_empty());
3112         assert!(updates.update_fulfill_htlcs.is_empty());
3113         assert!(updates.update_fail_malformed_htlcs.is_empty());
3114         assert_eq!(updates.update_fail_htlcs.len(), 1);
3115         assert!(updates.update_fee.is_none());
3116         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3117         let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3118         // Drop the last RAA from 3 -> 2
3119
3120         nodes[2].node.fail_htlc_backwards(&second_payment_hash);
3121         expect_pending_htlcs_forwardable!(nodes[2]);
3122         check_added_monitors!(nodes[2], 1);
3123         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3124         assert!(updates.update_add_htlcs.is_empty());
3125         assert!(updates.update_fulfill_htlcs.is_empty());
3126         assert!(updates.update_fail_malformed_htlcs.is_empty());
3127         assert_eq!(updates.update_fail_htlcs.len(), 1);
3128         assert!(updates.update_fee.is_none());
3129         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3130         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3131         check_added_monitors!(nodes[1], 1);
3132         // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3133         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3134         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3135         check_added_monitors!(nodes[2], 1);
3136
3137         nodes[2].node.fail_htlc_backwards(&third_payment_hash);
3138         expect_pending_htlcs_forwardable!(nodes[2]);
3139         check_added_monitors!(nodes[2], 1);
3140         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3141         assert!(updates.update_add_htlcs.is_empty());
3142         assert!(updates.update_fulfill_htlcs.is_empty());
3143         assert!(updates.update_fail_malformed_htlcs.is_empty());
3144         assert_eq!(updates.update_fail_htlcs.len(), 1);
3145         assert!(updates.update_fee.is_none());
3146         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3147         // At this point first_payment_hash has dropped out of the latest two commitment
3148         // transactions that nodes[1] is tracking...
3149         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3150         check_added_monitors!(nodes[1], 1);
3151         // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3152         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3153         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3154         check_added_monitors!(nodes[2], 1);
3155
3156         // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3157         // on nodes[2]'s RAA.
3158         let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3159         nodes[1].node.send_payment(&route, fourth_payment_hash, &Some(fourth_payment_secret)).unwrap();
3160         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3161         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3162         check_added_monitors!(nodes[1], 0);
3163
3164         if deliver_bs_raa {
3165                 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3166                 // One monitor for the new revocation preimage, no second on as we won't generate a new
3167                 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3168                 check_added_monitors!(nodes[1], 1);
3169                 let events = nodes[1].node.get_and_clear_pending_events();
3170                 assert_eq!(events.len(), 1);
3171                 match events[0] {
3172                         Event::PendingHTLCsForwardable { .. } => { },
3173                         _ => panic!("Unexpected event"),
3174                 };
3175                 // Deliberately don't process the pending fail-back so they all fail back at once after
3176                 // block connection just like the !deliver_bs_raa case
3177         }
3178
3179         let mut failed_htlcs = HashSet::new();
3180         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3181
3182         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3183         check_added_monitors!(nodes[1], 1);
3184         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3185         assert!(ANTI_REORG_DELAY > PAYMENT_EXPIRY_BLOCKS); // We assume payments will also expire
3186
3187         let events = nodes[1].node.get_and_clear_pending_events();
3188         assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 4 });
3189         match events[0] {
3190                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3191                 _ => panic!("Unexepected event"),
3192         }
3193         match events[1] {
3194                 Event::PaymentPathFailed { ref payment_hash, .. } => {
3195                         assert_eq!(*payment_hash, fourth_payment_hash);
3196                 },
3197                 _ => panic!("Unexpected event"),
3198         }
3199         if !deliver_bs_raa {
3200                 match events[2] {
3201                         Event::PaymentFailed { ref payment_hash, .. } => {
3202                                 assert_eq!(*payment_hash, fourth_payment_hash);
3203                         },
3204                         _ => panic!("Unexpected event"),
3205                 }
3206                 match events[3] {
3207                         Event::PendingHTLCsForwardable { .. } => { },
3208                         _ => panic!("Unexpected event"),
3209                 };
3210         }
3211         nodes[1].node.process_pending_htlc_forwards();
3212         check_added_monitors!(nodes[1], 1);
3213
3214         let events = nodes[1].node.get_and_clear_pending_msg_events();
3215         assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3216         match events[if deliver_bs_raa { 1 } else { 0 }] {
3217                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3218                 _ => panic!("Unexpected event"),
3219         }
3220         match events[if deliver_bs_raa { 2 } else { 1 }] {
3221                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3222                         assert_eq!(channel_id, chan_2.2);
3223                         assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3224                 },
3225                 _ => panic!("Unexpected event"),
3226         }
3227         if deliver_bs_raa {
3228                 match events[0] {
3229                         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, .. } } => {
3230                                 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3231                                 assert_eq!(update_add_htlcs.len(), 1);
3232                                 assert!(update_fulfill_htlcs.is_empty());
3233                                 assert!(update_fail_htlcs.is_empty());
3234                                 assert!(update_fail_malformed_htlcs.is_empty());
3235                         },
3236                         _ => panic!("Unexpected event"),
3237                 }
3238         }
3239         match events[if deliver_bs_raa { 3 } else { 2 }] {
3240                 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, .. } } => {
3241                         assert!(update_add_htlcs.is_empty());
3242                         assert_eq!(update_fail_htlcs.len(), 3);
3243                         assert!(update_fulfill_htlcs.is_empty());
3244                         assert!(update_fail_malformed_htlcs.is_empty());
3245                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3246
3247                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3248                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3249                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3250
3251                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3252
3253                         let events = nodes[0].node.get_and_clear_pending_events();
3254                         assert_eq!(events.len(), 3);
3255                         match events[0] {
3256                                 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3257                                         assert!(failed_htlcs.insert(payment_hash.0));
3258                                         // If we delivered B's RAA we got an unknown preimage error, not something
3259                                         // that we should update our routing table for.
3260                                         if !deliver_bs_raa {
3261                                                 assert!(network_update.is_some());
3262                                         }
3263                                 },
3264                                 _ => panic!("Unexpected event"),
3265                         }
3266                         match events[1] {
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                         match events[2] {
3274                                 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3275                                         assert!(failed_htlcs.insert(payment_hash.0));
3276                                         assert!(network_update.is_some());
3277                                 },
3278                                 _ => panic!("Unexpected event"),
3279                         }
3280                 },
3281                 _ => panic!("Unexpected event"),
3282         }
3283
3284         assert!(failed_htlcs.contains(&first_payment_hash.0));
3285         assert!(failed_htlcs.contains(&second_payment_hash.0));
3286         assert!(failed_htlcs.contains(&third_payment_hash.0));
3287 }
3288
3289 #[test]
3290 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3291         do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3292         do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3293         do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3294         do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3295 }
3296
3297 #[test]
3298 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3299         do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3300         do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3301         do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3302         do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3303 }
3304
3305 #[test]
3306 fn fail_backward_pending_htlc_upon_channel_failure() {
3307         let chanmon_cfgs = create_chanmon_cfgs(2);
3308         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3309         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3310         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3311         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
3312
3313         // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3314         {
3315                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3316                 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
3317                 check_added_monitors!(nodes[0], 1);
3318
3319                 let payment_event = {
3320                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3321                         assert_eq!(events.len(), 1);
3322                         SendEvent::from_event(events.remove(0))
3323                 };
3324                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3325                 assert_eq!(payment_event.msgs.len(), 1);
3326         }
3327
3328         // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3329         let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3330         {
3331                 nodes[0].node.send_payment(&route, failed_payment_hash, &Some(failed_payment_secret)).unwrap();
3332                 check_added_monitors!(nodes[0], 0);
3333
3334                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3335         }
3336
3337         // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3338         {
3339                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3340
3341                 let secp_ctx = Secp256k1::new();
3342                 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3343                 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3344                 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &Some(payment_secret), current_height, &None).unwrap();
3345                 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3346                 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3347
3348                 // Send a 0-msat update_add_htlc to fail the channel.
3349                 let update_add_htlc = msgs::UpdateAddHTLC {
3350                         channel_id: chan.2,
3351                         htlc_id: 0,
3352                         amount_msat: 0,
3353                         payment_hash,
3354                         cltv_expiry,
3355                         onion_routing_packet,
3356                 };
3357                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3358         }
3359         let events = nodes[0].node.get_and_clear_pending_events();
3360         assert_eq!(events.len(), 2);
3361         // Check that Alice fails backward the pending HTLC from the second payment.
3362         match events[0] {
3363                 Event::PaymentPathFailed { payment_hash, .. } => {
3364                         assert_eq!(payment_hash, failed_payment_hash);
3365                 },
3366                 _ => panic!("Unexpected event"),
3367         }
3368         match events[1] {
3369                 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3370                         assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3371                 },
3372                 _ => panic!("Unexpected event {:?}", events[1]),
3373         }
3374         check_closed_broadcast!(nodes[0], true);
3375         check_added_monitors!(nodes[0], 1);
3376 }
3377
3378 #[test]
3379 fn test_htlc_ignore_latest_remote_commitment() {
3380         // Test that HTLC transactions spending the latest remote commitment transaction are simply
3381         // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3382         let chanmon_cfgs = create_chanmon_cfgs(2);
3383         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3384         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3385         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3386         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3387
3388         route_payment(&nodes[0], &[&nodes[1]], 10000000);
3389         nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3390         connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3391         check_closed_broadcast!(nodes[0], true);
3392         check_added_monitors!(nodes[0], 1);
3393         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
3394
3395         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3396         assert_eq!(node_txn.len(), 3);
3397         assert_eq!(node_txn[0], node_txn[1]);
3398
3399         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3400         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3401         check_closed_broadcast!(nodes[1], true);
3402         check_added_monitors!(nodes[1], 1);
3403         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3404
3405         // Duplicate the connect_block call since this may happen due to other listeners
3406         // registering new transactions
3407         header.prev_blockhash = header.block_hash();
3408         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[2].clone()]});
3409 }
3410
3411 #[test]
3412 fn test_force_close_fail_back() {
3413         // Check which HTLCs are failed-backwards on channel force-closure
3414         let chanmon_cfgs = create_chanmon_cfgs(3);
3415         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3416         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3417         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3418         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3419         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3420
3421         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3422
3423         let mut payment_event = {
3424                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
3425                 check_added_monitors!(nodes[0], 1);
3426
3427                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3428                 assert_eq!(events.len(), 1);
3429                 SendEvent::from_event(events.remove(0))
3430         };
3431
3432         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3433         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3434
3435         expect_pending_htlcs_forwardable!(nodes[1]);
3436
3437         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3438         assert_eq!(events_2.len(), 1);
3439         payment_event = SendEvent::from_event(events_2.remove(0));
3440         assert_eq!(payment_event.msgs.len(), 1);
3441
3442         check_added_monitors!(nodes[1], 1);
3443         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3444         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3445         check_added_monitors!(nodes[2], 1);
3446         let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3447
3448         // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3449         // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3450         // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3451
3452         nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3453         check_closed_broadcast!(nodes[2], true);
3454         check_added_monitors!(nodes[2], 1);
3455         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
3456         let tx = {
3457                 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3458                 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3459                 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3460                 // back to nodes[1] upon timeout otherwise.
3461                 assert_eq!(node_txn.len(), 1);
3462                 node_txn.remove(0)
3463         };
3464
3465         mine_transaction(&nodes[1], &tx);
3466
3467         // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3468         check_closed_broadcast!(nodes[1], true);
3469         check_added_monitors!(nodes[1], 1);
3470         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3471
3472         // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3473         {
3474                 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3475                         .provide_payment_preimage(&our_payment_hash, &our_payment_preimage, &node_cfgs[2].tx_broadcaster, &node_cfgs[2].fee_estimator, &node_cfgs[2].logger);
3476         }
3477         mine_transaction(&nodes[2], &tx);
3478         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3479         assert_eq!(node_txn.len(), 1);
3480         assert_eq!(node_txn[0].input.len(), 1);
3481         assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3482         assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3483         assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3484
3485         check_spends!(node_txn[0], tx);
3486 }
3487
3488 #[test]
3489 fn test_dup_events_on_peer_disconnect() {
3490         // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3491         // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3492         // as we used to generate the event immediately upon receipt of the payment preimage in the
3493         // update_fulfill_htlc message.
3494
3495         let chanmon_cfgs = create_chanmon_cfgs(2);
3496         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3497         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3498         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3499         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3500
3501         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3502
3503         nodes[1].node.claim_funds(payment_preimage);
3504         expect_payment_claimed!(nodes[1], payment_hash, 1_000_000);
3505         check_added_monitors!(nodes[1], 1);
3506         let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3507         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3508         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
3509
3510         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3511         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3512
3513         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3514         expect_payment_path_successful!(nodes[0]);
3515 }
3516
3517 #[test]
3518 fn test_peer_disconnected_before_funding_broadcasted() {
3519         // Test that channels are closed with `ClosureReason::DisconnectedPeer` if the peer disconnects
3520         // before the funding transaction has been broadcasted.
3521         let chanmon_cfgs = create_chanmon_cfgs(2);
3522         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3523         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3524         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3525
3526         // Open a channel between `nodes[0]` and `nodes[1]`, for which the funding transaction is never
3527         // broadcasted, even though it's created by `nodes[0]`.
3528         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();
3529         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
3530         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
3531         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
3532         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
3533
3534         let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
3535         assert_eq!(temporary_channel_id, expected_temporary_channel_id);
3536
3537         assert!(nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
3538
3539         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
3540         assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
3541
3542         // Even though the funding transaction is created by `nodes[0]`, the `FundingCreated` msg is
3543         // never sent to `nodes[1]`, and therefore the tx is never signed by either party nor
3544         // broadcasted.
3545         {
3546                 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
3547         }
3548
3549         // Ensure that the channel is closed with `ClosureReason::DisconnectedPeer` when the peers are
3550         // disconnected before the funding transaction was broadcasted.
3551         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3552         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3553
3554         check_closed_event!(nodes[0], 1, ClosureReason::DisconnectedPeer);
3555         check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
3556 }
3557
3558 #[test]
3559 fn test_simple_peer_disconnect() {
3560         // Test that we can reconnect when there are no lost messages
3561         let chanmon_cfgs = create_chanmon_cfgs(3);
3562         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3563         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3564         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3565         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3566         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3567
3568         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3569         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3570         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3571
3572         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3573         let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3574         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3575         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3576
3577         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3578         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3579         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3580
3581         let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3582         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3583         let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3584         let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3585
3586         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3587         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3588
3589         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3590         fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3591
3592         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3593         {
3594                 let events = nodes[0].node.get_and_clear_pending_events();
3595                 assert_eq!(events.len(), 3);
3596                 match events[0] {
3597                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3598                                 assert_eq!(payment_preimage, payment_preimage_3);
3599                                 assert_eq!(payment_hash, payment_hash_3);
3600                         },
3601                         _ => panic!("Unexpected event"),
3602                 }
3603                 match events[1] {
3604                         Event::PaymentPathFailed { payment_hash, rejected_by_dest, .. } => {
3605                                 assert_eq!(payment_hash, payment_hash_5);
3606                                 assert!(rejected_by_dest);
3607                         },
3608                         _ => panic!("Unexpected event"),
3609                 }
3610                 match events[2] {
3611                         Event::PaymentPathSuccessful { .. } => {},
3612                         _ => panic!("Unexpected event"),
3613                 }
3614         }
3615
3616         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3617         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3618 }
3619
3620 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3621         // Test that we can reconnect when in-flight HTLC updates get dropped
3622         let chanmon_cfgs = create_chanmon_cfgs(2);
3623         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3624         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3625         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3626
3627         let mut as_channel_ready = None;
3628         if messages_delivered == 0 {
3629                 let (channel_ready, _, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3630                 as_channel_ready = Some(channel_ready);
3631                 // nodes[1] doesn't receive the channel_ready message (it'll be re-sent on reconnect)
3632                 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3633                 // it before the channel_reestablish message.
3634         } else {
3635                 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3636         }
3637
3638         let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1_000_000);
3639
3640         let payment_event = {
3641                 nodes[0].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)).unwrap();
3642                 check_added_monitors!(nodes[0], 1);
3643
3644                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3645                 assert_eq!(events.len(), 1);
3646                 SendEvent::from_event(events.remove(0))
3647         };
3648         assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3649
3650         if messages_delivered < 2 {
3651                 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3652         } else {
3653                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3654                 if messages_delivered >= 3 {
3655                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3656                         check_added_monitors!(nodes[1], 1);
3657                         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3658
3659                         if messages_delivered >= 4 {
3660                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3661                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3662                                 check_added_monitors!(nodes[0], 1);
3663
3664                                 if messages_delivered >= 5 {
3665                                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3666                                         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3667                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3668                                         check_added_monitors!(nodes[0], 1);
3669
3670                                         if messages_delivered >= 6 {
3671                                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3672                                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3673                                                 check_added_monitors!(nodes[1], 1);
3674                                         }
3675                                 }
3676                         }
3677                 }
3678         }
3679
3680         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3681         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3682         if messages_delivered < 3 {
3683                 if simulate_broken_lnd {
3684                         // lnd has a long-standing bug where they send a channel_ready prior to a
3685                         // channel_reestablish if you reconnect prior to channel_ready time.
3686                         //
3687                         // Here we simulate that behavior, delivering a channel_ready immediately on
3688                         // reconnect. Note that we don't bother skipping the now-duplicate channel_ready sent
3689                         // in `reconnect_nodes` but we currently don't fail based on that.
3690                         //
3691                         // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3692                         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready.as_ref().unwrap().0);
3693                 }
3694                 // Even if the channel_ready messages get exchanged, as long as nothing further was
3695                 // received on either side, both sides will need to resend them.
3696                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3697         } else if messages_delivered == 3 {
3698                 // nodes[0] still wants its RAA + commitment_signed
3699                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3700         } else if messages_delivered == 4 {
3701                 // nodes[0] still wants its commitment_signed
3702                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3703         } else if messages_delivered == 5 {
3704                 // nodes[1] still wants its final RAA
3705                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3706         } else if messages_delivered == 6 {
3707                 // Everything was delivered...
3708                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3709         }
3710
3711         let events_1 = nodes[1].node.get_and_clear_pending_events();
3712         assert_eq!(events_1.len(), 1);
3713         match events_1[0] {
3714                 Event::PendingHTLCsForwardable { .. } => { },
3715                 _ => panic!("Unexpected event"),
3716         };
3717
3718         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3719         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3720         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3721
3722         nodes[1].node.process_pending_htlc_forwards();
3723
3724         let events_2 = nodes[1].node.get_and_clear_pending_events();
3725         assert_eq!(events_2.len(), 1);
3726         match events_2[0] {
3727                 Event::PaymentReceived { ref payment_hash, ref purpose, amount_msat } => {
3728                         assert_eq!(payment_hash_1, *payment_hash);
3729                         assert_eq!(amount_msat, 1_000_000);
3730                         match &purpose {
3731                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3732                                         assert!(payment_preimage.is_none());
3733                                         assert_eq!(payment_secret_1, *payment_secret);
3734                                 },
3735                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
3736                         }
3737                 },
3738                 _ => panic!("Unexpected event"),
3739         }
3740
3741         nodes[1].node.claim_funds(payment_preimage_1);
3742         check_added_monitors!(nodes[1], 1);
3743         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3744
3745         let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3746         assert_eq!(events_3.len(), 1);
3747         let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3748                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3749                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3750                         assert!(updates.update_add_htlcs.is_empty());
3751                         assert!(updates.update_fail_htlcs.is_empty());
3752                         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3753                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3754                         assert!(updates.update_fee.is_none());
3755                         (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3756                 },
3757                 _ => panic!("Unexpected event"),
3758         };
3759
3760         if messages_delivered >= 1 {
3761                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3762
3763                 let events_4 = nodes[0].node.get_and_clear_pending_events();
3764                 assert_eq!(events_4.len(), 1);
3765                 match events_4[0] {
3766                         Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3767                                 assert_eq!(payment_preimage_1, *payment_preimage);
3768                                 assert_eq!(payment_hash_1, *payment_hash);
3769                         },
3770                         _ => panic!("Unexpected event"),
3771                 }
3772
3773                 if messages_delivered >= 2 {
3774                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3775                         check_added_monitors!(nodes[0], 1);
3776                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3777
3778                         if messages_delivered >= 3 {
3779                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3780                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3781                                 check_added_monitors!(nodes[1], 1);
3782
3783                                 if messages_delivered >= 4 {
3784                                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3785                                         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3786                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3787                                         check_added_monitors!(nodes[1], 1);
3788
3789                                         if messages_delivered >= 5 {
3790                                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3791                                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3792                                                 check_added_monitors!(nodes[0], 1);
3793                                         }
3794                                 }
3795                         }
3796                 }
3797         }
3798
3799         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3800         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3801         if messages_delivered < 2 {
3802                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3803                 if messages_delivered < 1 {
3804                         expect_payment_sent!(nodes[0], payment_preimage_1);
3805                 } else {
3806                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3807                 }
3808         } else if messages_delivered == 2 {
3809                 // nodes[0] still wants its RAA + commitment_signed
3810                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3811         } else if messages_delivered == 3 {
3812                 // nodes[0] still wants its commitment_signed
3813                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3814         } else if messages_delivered == 4 {
3815                 // nodes[1] still wants its final RAA
3816                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3817         } else if messages_delivered == 5 {
3818                 // Everything was delivered...
3819                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3820         }
3821
3822         if messages_delivered == 1 || messages_delivered == 2 {
3823                 expect_payment_path_successful!(nodes[0]);
3824         }
3825
3826         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3827         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3828         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3829
3830         if messages_delivered > 2 {
3831                 expect_payment_path_successful!(nodes[0]);
3832         }
3833
3834         // Channel should still work fine...
3835         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3836         let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3837         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3838 }
3839
3840 #[test]
3841 fn test_drop_messages_peer_disconnect_a() {
3842         do_test_drop_messages_peer_disconnect(0, true);
3843         do_test_drop_messages_peer_disconnect(0, false);
3844         do_test_drop_messages_peer_disconnect(1, false);
3845         do_test_drop_messages_peer_disconnect(2, false);
3846 }
3847
3848 #[test]
3849 fn test_drop_messages_peer_disconnect_b() {
3850         do_test_drop_messages_peer_disconnect(3, false);
3851         do_test_drop_messages_peer_disconnect(4, false);
3852         do_test_drop_messages_peer_disconnect(5, false);
3853         do_test_drop_messages_peer_disconnect(6, false);
3854 }
3855
3856 #[test]
3857 fn test_funding_peer_disconnect() {
3858         // Test that we can lock in our funding tx while disconnected
3859         let chanmon_cfgs = create_chanmon_cfgs(2);
3860         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3861         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3862         let persister: test_utils::TestPersister;
3863         let new_chain_monitor: test_utils::TestChainMonitor;
3864         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
3865         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3866         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
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[0], &tx);
3872         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3873         assert!(events_1.is_empty());
3874
3875         reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3876
3877         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3878         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3879
3880         confirm_transaction(&nodes[1], &tx);
3881         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3882         assert!(events_2.is_empty());
3883
3884         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
3885         let as_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
3886         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
3887         let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
3888
3889         // nodes[0] hasn't yet received a channel_ready, so it only sends that on reconnect.
3890         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
3891         let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3892         assert_eq!(events_3.len(), 1);
3893         let as_channel_ready = match events_3[0] {
3894                 MessageSendEvent::SendChannelReady { ref node_id, ref msg } => {
3895                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3896                         msg.clone()
3897                 },
3898                 _ => panic!("Unexpected event {:?}", events_3[0]),
3899         };
3900
3901         // nodes[1] received nodes[0]'s channel_ready on the first reconnect above, so it should send
3902         // announcement_signatures as well as channel_update.
3903         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reestablish);
3904         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3905         assert_eq!(events_4.len(), 3);
3906         let chan_id;
3907         let bs_channel_ready = match events_4[0] {
3908                 MessageSendEvent::SendChannelReady { ref node_id, ref msg } => {
3909                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3910                         chan_id = msg.channel_id;
3911                         msg.clone()
3912                 },
3913                 _ => panic!("Unexpected event {:?}", events_4[0]),
3914         };
3915         let bs_announcement_sigs = match events_4[1] {
3916                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3917                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3918                         msg.clone()
3919                 },
3920                 _ => panic!("Unexpected event {:?}", events_4[1]),
3921         };
3922         match events_4[2] {
3923                 MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } => {
3924                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3925                 },
3926                 _ => panic!("Unexpected event {:?}", events_4[2]),
3927         }
3928
3929         // Re-deliver nodes[0]'s channel_ready, which nodes[1] can safely ignore. It currently
3930         // generates a duplicative private channel_update
3931         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
3932         let events_5 = nodes[1].node.get_and_clear_pending_msg_events();
3933         assert_eq!(events_5.len(), 1);
3934         match events_5[0] {
3935                 MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } => {
3936                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3937                 },
3938                 _ => panic!("Unexpected event {:?}", events_5[0]),
3939         };
3940
3941         // When we deliver nodes[1]'s channel_ready, however, nodes[0] will generate its
3942         // announcement_signatures.
3943         nodes[0].node.handle_channel_ready(&nodes[1].node.get_our_node_id(), &bs_channel_ready);
3944         let events_6 = nodes[0].node.get_and_clear_pending_msg_events();
3945         assert_eq!(events_6.len(), 1);
3946         let as_announcement_sigs = match events_6[0] {
3947                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3948                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3949                         msg.clone()
3950                 },
3951                 _ => panic!("Unexpected event {:?}", events_6[0]),
3952         };
3953
3954         // When we deliver nodes[1]'s announcement_signatures to nodes[0], nodes[0] should immediately
3955         // broadcast the channel announcement globally, as well as re-send its (now-public)
3956         // channel_update.
3957         nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3958         let events_7 = nodes[0].node.get_and_clear_pending_msg_events();
3959         assert_eq!(events_7.len(), 1);
3960         let (chan_announcement, as_update) = match events_7[0] {
3961                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3962                         (msg.clone(), update_msg.clone())
3963                 },
3964                 _ => panic!("Unexpected event {:?}", events_7[0]),
3965         };
3966
3967         // Finally, deliver nodes[0]'s announcement_signatures to nodes[1] and make sure it creates the
3968         // same channel_announcement.
3969         nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3970         let events_8 = nodes[1].node.get_and_clear_pending_msg_events();
3971         assert_eq!(events_8.len(), 1);
3972         let bs_update = match events_8[0] {
3973                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3974                         assert_eq!(*msg, chan_announcement);
3975                         update_msg.clone()
3976                 },
3977                 _ => panic!("Unexpected event {:?}", events_8[0]),
3978         };
3979
3980         // Provide the channel announcement and public updates to the network graph
3981         nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).unwrap();
3982         nodes[0].net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
3983         nodes[0].net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
3984
3985         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3986         let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3987         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
3988
3989         // Check that after deserialization and reconnection we can still generate an identical
3990         // channel_announcement from the cached signatures.
3991         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3992
3993         let nodes_0_serialized = nodes[0].node.encode();
3994         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
3995         get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
3996
3997         persister = test_utils::TestPersister::new();
3998         let keys_manager = &chanmon_cfgs[0].keys_manager;
3999         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);
4000         nodes[0].chain_monitor = &new_chain_monitor;
4001         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4002         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4003                 &mut chan_0_monitor_read, keys_manager).unwrap();
4004         assert!(chan_0_monitor_read.is_empty());
4005
4006         let mut nodes_0_read = &nodes_0_serialized[..];
4007         let (_, nodes_0_deserialized_tmp) = {
4008                 let mut channel_monitors = HashMap::new();
4009                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4010                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4011                         default_config: UserConfig::default(),
4012                         keys_manager,
4013                         fee_estimator: node_cfgs[0].fee_estimator,
4014                         chain_monitor: nodes[0].chain_monitor,
4015                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4016                         logger: nodes[0].logger,
4017                         channel_monitors,
4018                 }).unwrap()
4019         };
4020         nodes_0_deserialized = nodes_0_deserialized_tmp;
4021         assert!(nodes_0_read.is_empty());
4022
4023         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4024         nodes[0].node = &nodes_0_deserialized;
4025         check_added_monitors!(nodes[0], 1);
4026
4027         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4028
4029         // The channel announcement should be re-generated exactly by broadcast_node_announcement.
4030         nodes[0].node.broadcast_node_announcement([0, 0, 0], [0; 32], Vec::new());
4031         let msgs = nodes[0].node.get_and_clear_pending_msg_events();
4032         let mut found_announcement = false;
4033         for event in msgs.iter() {
4034                 match event {
4035                         MessageSendEvent::BroadcastChannelAnnouncement { ref msg, .. } => {
4036                                 if *msg == chan_announcement { found_announcement = true; }
4037                         },
4038                         MessageSendEvent::BroadcastNodeAnnouncement { .. } => {},
4039                         _ => panic!("Unexpected event"),
4040                 }
4041         }
4042         assert!(found_announcement);
4043 }
4044
4045 #[test]
4046 fn test_channel_ready_without_best_block_updated() {
4047         // Previously, if we were offline when a funding transaction was locked in, and then we came
4048         // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
4049         // generate a channel_ready until a later best_block_updated. This tests that we generate the
4050         // channel_ready immediately instead.
4051         let chanmon_cfgs = create_chanmon_cfgs(2);
4052         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4053         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4054         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4055         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
4056
4057         let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
4058
4059         let conf_height = nodes[0].best_block_info().1 + 1;
4060         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
4061         let block_txn = [funding_tx];
4062         let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
4063         let conf_block_header = nodes[0].get_block_header(conf_height);
4064         nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
4065
4066         // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
4067         let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
4068         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
4069 }
4070
4071 #[test]
4072 fn test_drop_messages_peer_disconnect_dual_htlc() {
4073         // Test that we can handle reconnecting when both sides of a channel have pending
4074         // commitment_updates when we disconnect.
4075         let chanmon_cfgs = create_chanmon_cfgs(2);
4076         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4077         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4078         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4079         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4080
4081         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
4082
4083         // Now try to send a second payment which will fail to send
4084         let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
4085         nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
4086         check_added_monitors!(nodes[0], 1);
4087
4088         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
4089         assert_eq!(events_1.len(), 1);
4090         match events_1[0] {
4091                 MessageSendEvent::UpdateHTLCs { .. } => {},
4092                 _ => panic!("Unexpected event"),
4093         }
4094
4095         nodes[1].node.claim_funds(payment_preimage_1);
4096         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
4097         check_added_monitors!(nodes[1], 1);
4098
4099         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
4100         assert_eq!(events_2.len(), 1);
4101         match events_2[0] {
4102                 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 } } => {
4103                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
4104                         assert!(update_add_htlcs.is_empty());
4105                         assert_eq!(update_fulfill_htlcs.len(), 1);
4106                         assert!(update_fail_htlcs.is_empty());
4107                         assert!(update_fail_malformed_htlcs.is_empty());
4108                         assert!(update_fee.is_none());
4109
4110                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
4111                         let events_3 = nodes[0].node.get_and_clear_pending_events();
4112                         assert_eq!(events_3.len(), 1);
4113                         match events_3[0] {
4114                                 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4115                                         assert_eq!(*payment_preimage, payment_preimage_1);
4116                                         assert_eq!(*payment_hash, payment_hash_1);
4117                                 },
4118                                 _ => panic!("Unexpected event"),
4119                         }
4120
4121                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
4122                         let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4123                         // No commitment_signed so get_event_msg's assert(len == 1) passes
4124                         check_added_monitors!(nodes[0], 1);
4125                 },
4126                 _ => panic!("Unexpected event"),
4127         }
4128
4129         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
4130         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4131
4132         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4133         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4134         assert_eq!(reestablish_1.len(), 1);
4135         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4136         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4137         assert_eq!(reestablish_2.len(), 1);
4138
4139         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4140         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4141         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4142         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4143
4144         assert!(as_resp.0.is_none());
4145         assert!(bs_resp.0.is_none());
4146
4147         assert!(bs_resp.1.is_none());
4148         assert!(bs_resp.2.is_none());
4149
4150         assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4151
4152         assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4153         assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4154         assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4155         assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4156         assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4157         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4158         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4159         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4160         // No commitment_signed so get_event_msg's assert(len == 1) passes
4161         check_added_monitors!(nodes[1], 1);
4162
4163         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4164         let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4165         assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4166         assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4167         assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4168         assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4169         assert!(bs_second_commitment_signed.update_fee.is_none());
4170         check_added_monitors!(nodes[1], 1);
4171
4172         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4173         let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4174         assert!(as_commitment_signed.update_add_htlcs.is_empty());
4175         assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4176         assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4177         assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4178         assert!(as_commitment_signed.update_fee.is_none());
4179         check_added_monitors!(nodes[0], 1);
4180
4181         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4182         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4183         // No commitment_signed so get_event_msg's assert(len == 1) passes
4184         check_added_monitors!(nodes[0], 1);
4185
4186         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4187         let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4188         // No commitment_signed so get_event_msg's assert(len == 1) passes
4189         check_added_monitors!(nodes[1], 1);
4190
4191         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4192         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4193         check_added_monitors!(nodes[1], 1);
4194
4195         expect_pending_htlcs_forwardable!(nodes[1]);
4196
4197         let events_5 = nodes[1].node.get_and_clear_pending_events();
4198         assert_eq!(events_5.len(), 1);
4199         match events_5[0] {
4200                 Event::PaymentReceived { ref payment_hash, ref purpose, .. } => {
4201                         assert_eq!(payment_hash_2, *payment_hash);
4202                         match &purpose {
4203                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4204                                         assert!(payment_preimage.is_none());
4205                                         assert_eq!(payment_secret_2, *payment_secret);
4206                                 },
4207                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
4208                         }
4209                 },
4210                 _ => panic!("Unexpected event"),
4211         }
4212
4213         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4214         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4215         check_added_monitors!(nodes[0], 1);
4216
4217         expect_payment_path_successful!(nodes[0]);
4218         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4219 }
4220
4221 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4222         // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4223         // to avoid our counterparty failing the channel.
4224         let chanmon_cfgs = create_chanmon_cfgs(2);
4225         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4226         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4227         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4228
4229         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4230
4231         let our_payment_hash = if send_partial_mpp {
4232                 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4233                 // Use the utility function send_payment_along_path to send the payment with MPP data which
4234                 // indicates there are more HTLCs coming.
4235                 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.
4236                 let payment_id = PaymentId([42; 32]);
4237                 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();
4238                 check_added_monitors!(nodes[0], 1);
4239                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4240                 assert_eq!(events.len(), 1);
4241                 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4242                 // hop should *not* yet generate any PaymentReceived event(s).
4243                 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4244                 our_payment_hash
4245         } else {
4246                 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4247         };
4248
4249         let mut block = Block {
4250                 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
4251                 txdata: vec![],
4252         };
4253         connect_block(&nodes[0], &block);
4254         connect_block(&nodes[1], &block);
4255         let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4256         for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4257                 block.header.prev_blockhash = block.block_hash();
4258                 connect_block(&nodes[0], &block);
4259                 connect_block(&nodes[1], &block);
4260         }
4261
4262         expect_pending_htlcs_forwardable!(nodes[1]);
4263
4264         check_added_monitors!(nodes[1], 1);
4265         let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4266         assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4267         assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4268         assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4269         assert!(htlc_timeout_updates.update_fee.is_none());
4270
4271         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4272         commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4273         // 100_000 msat as u64, followed by the height at which we failed back above
4274         let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
4275         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(block_count - 1));
4276         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4277 }
4278
4279 #[test]
4280 fn test_htlc_timeout() {
4281         do_test_htlc_timeout(true);
4282         do_test_htlc_timeout(false);
4283 }
4284
4285 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4286         // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4287         let chanmon_cfgs = create_chanmon_cfgs(3);
4288         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4289         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4290         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4291         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4292         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4293
4294         // Make sure all nodes are at the same starting height
4295         connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4296         connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4297         connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4298
4299         // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4300         let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4301         {
4302                 nodes[1].node.send_payment(&route, first_payment_hash, &Some(first_payment_secret)).unwrap();
4303         }
4304         assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4305         check_added_monitors!(nodes[1], 1);
4306
4307         // Now attempt to route a second payment, which should be placed in the holding cell
4308         let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4309         let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4310         sending_node.node.send_payment(&route, second_payment_hash, &Some(second_payment_secret)).unwrap();
4311         if forwarded_htlc {
4312                 check_added_monitors!(nodes[0], 1);
4313                 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4314                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4315                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4316                 expect_pending_htlcs_forwardable!(nodes[1]);
4317         }
4318         check_added_monitors!(nodes[1], 0);
4319
4320         connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4321         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4322         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4323         connect_blocks(&nodes[1], 1);
4324
4325         if forwarded_htlc {
4326                 expect_pending_htlcs_forwardable!(nodes[1]);
4327                 check_added_monitors!(nodes[1], 1);
4328                 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4329                 assert_eq!(fail_commit.len(), 1);
4330                 match fail_commit[0] {
4331                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4332                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4333                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4334                         },
4335                         _ => unreachable!(),
4336                 }
4337                 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4338         } else {
4339                 let events = nodes[1].node.get_and_clear_pending_events();
4340                 assert_eq!(events.len(), 2);
4341                 if let Event::PaymentPathFailed { ref payment_hash, .. } = events[0] {
4342                         assert_eq!(*payment_hash, second_payment_hash);
4343                 } else { panic!("Unexpected event"); }
4344                 if let Event::PaymentFailed { ref payment_hash, .. } = events[1] {
4345                         assert_eq!(*payment_hash, second_payment_hash);
4346                 } else { panic!("Unexpected event"); }
4347         }
4348 }
4349
4350 #[test]
4351 fn test_holding_cell_htlc_add_timeouts() {
4352         do_test_holding_cell_htlc_add_timeouts(false);
4353         do_test_holding_cell_htlc_add_timeouts(true);
4354 }
4355
4356 #[test]
4357 fn test_no_txn_manager_serialize_deserialize() {
4358         let chanmon_cfgs = create_chanmon_cfgs(2);
4359         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4360         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4361         let logger: test_utils::TestLogger;
4362         let fee_estimator: test_utils::TestFeeEstimator;
4363         let persister: test_utils::TestPersister;
4364         let new_chain_monitor: test_utils::TestChainMonitor;
4365         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4366         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4367
4368         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
4369
4370         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4371
4372         let nodes_0_serialized = nodes[0].node.encode();
4373         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4374         get_monitor!(nodes[0], OutPoint { txid: tx.txid(), index: 0 }.to_channel_id())
4375                 .write(&mut chan_0_monitor_serialized).unwrap();
4376
4377         logger = test_utils::TestLogger::new();
4378         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4379         persister = test_utils::TestPersister::new();
4380         let keys_manager = &chanmon_cfgs[0].keys_manager;
4381         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4382         nodes[0].chain_monitor = &new_chain_monitor;
4383         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4384         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4385                 &mut chan_0_monitor_read, keys_manager).unwrap();
4386         assert!(chan_0_monitor_read.is_empty());
4387
4388         let mut nodes_0_read = &nodes_0_serialized[..];
4389         let config = UserConfig::default();
4390         let (_, nodes_0_deserialized_tmp) = {
4391                 let mut channel_monitors = HashMap::new();
4392                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4393                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4394                         default_config: config,
4395                         keys_manager,
4396                         fee_estimator: &fee_estimator,
4397                         chain_monitor: nodes[0].chain_monitor,
4398                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4399                         logger: &logger,
4400                         channel_monitors,
4401                 }).unwrap()
4402         };
4403         nodes_0_deserialized = nodes_0_deserialized_tmp;
4404         assert!(nodes_0_read.is_empty());
4405
4406         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4407         nodes[0].node = &nodes_0_deserialized;
4408         assert_eq!(nodes[0].node.list_channels().len(), 1);
4409         check_added_monitors!(nodes[0], 1);
4410
4411         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4412         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4413         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4414         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4415
4416         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4417         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4418         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4419         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4420
4421         let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4422         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
4423         for node in nodes.iter() {
4424                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4425                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4426                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4427         }
4428
4429         send_payment(&nodes[0], &[&nodes[1]], 1000000);
4430 }
4431
4432 #[test]
4433 fn test_manager_serialize_deserialize_events() {
4434         // This test makes sure the events field in ChannelManager survives de/serialization
4435         let chanmon_cfgs = create_chanmon_cfgs(2);
4436         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4437         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4438         let fee_estimator: test_utils::TestFeeEstimator;
4439         let persister: test_utils::TestPersister;
4440         let logger: test_utils::TestLogger;
4441         let new_chain_monitor: test_utils::TestChainMonitor;
4442         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4443         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4444
4445         // Start creating a channel, but stop right before broadcasting the funding transaction
4446         let channel_value = 100000;
4447         let push_msat = 10001;
4448         let a_flags = InitFeatures::known();
4449         let b_flags = InitFeatures::known();
4450         let node_a = nodes.remove(0);
4451         let node_b = nodes.remove(0);
4452         node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
4453         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()));
4454         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()));
4455
4456         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, &node_b.node.get_our_node_id(), channel_value, 42);
4457
4458         node_a.node.funding_transaction_generated(&temporary_channel_id, &node_b.node.get_our_node_id(), tx.clone()).unwrap();
4459         check_added_monitors!(node_a, 0);
4460
4461         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()));
4462         {
4463                 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
4464                 assert_eq!(added_monitors.len(), 1);
4465                 assert_eq!(added_monitors[0].0, funding_output);
4466                 added_monitors.clear();
4467         }
4468
4469         let bs_funding_signed = get_event_msg!(node_b, MessageSendEvent::SendFundingSigned, node_a.node.get_our_node_id());
4470         node_a.node.handle_funding_signed(&node_b.node.get_our_node_id(), &bs_funding_signed);
4471         {
4472                 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
4473                 assert_eq!(added_monitors.len(), 1);
4474                 assert_eq!(added_monitors[0].0, funding_output);
4475                 added_monitors.clear();
4476         }
4477         // Normally, this is where node_a would broadcast the funding transaction, but the test de/serializes first instead
4478
4479         nodes.push(node_a);
4480         nodes.push(node_b);
4481
4482         // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4483         let nodes_0_serialized = nodes[0].node.encode();
4484         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4485         get_monitor!(nodes[0], bs_funding_signed.channel_id).write(&mut chan_0_monitor_serialized).unwrap();
4486
4487         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4488         logger = test_utils::TestLogger::new();
4489         persister = test_utils::TestPersister::new();
4490         let keys_manager = &chanmon_cfgs[0].keys_manager;
4491         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4492         nodes[0].chain_monitor = &new_chain_monitor;
4493         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4494         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4495                 &mut chan_0_monitor_read, keys_manager).unwrap();
4496         assert!(chan_0_monitor_read.is_empty());
4497
4498         let mut nodes_0_read = &nodes_0_serialized[..];
4499         let config = UserConfig::default();
4500         let (_, nodes_0_deserialized_tmp) = {
4501                 let mut channel_monitors = HashMap::new();
4502                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4503                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4504                         default_config: config,
4505                         keys_manager,
4506                         fee_estimator: &fee_estimator,
4507                         chain_monitor: nodes[0].chain_monitor,
4508                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4509                         logger: &logger,
4510                         channel_monitors,
4511                 }).unwrap()
4512         };
4513         nodes_0_deserialized = nodes_0_deserialized_tmp;
4514         assert!(nodes_0_read.is_empty());
4515
4516         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4517
4518         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4519         nodes[0].node = &nodes_0_deserialized;
4520
4521         // After deserializing, make sure the funding_transaction is still held by the channel manager
4522         let events_4 = nodes[0].node.get_and_clear_pending_events();
4523         assert_eq!(events_4.len(), 0);
4524         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
4525         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
4526
4527         // Make sure the channel is functioning as though the de/serialization never happened
4528         assert_eq!(nodes[0].node.list_channels().len(), 1);
4529         check_added_monitors!(nodes[0], 1);
4530
4531         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4532         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4533         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4534         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4535
4536         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4537         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4538         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4539         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4540
4541         let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4542         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
4543         for node in nodes.iter() {
4544                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4545                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4546                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4547         }
4548
4549         send_payment(&nodes[0], &[&nodes[1]], 1000000);
4550 }
4551
4552 #[test]
4553 fn test_simple_manager_serialize_deserialize() {
4554         let chanmon_cfgs = create_chanmon_cfgs(2);
4555         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4556         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4557         let logger: test_utils::TestLogger;
4558         let fee_estimator: test_utils::TestFeeEstimator;
4559         let persister: test_utils::TestPersister;
4560         let new_chain_monitor: test_utils::TestChainMonitor;
4561         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4562         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4563         let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
4564
4565         let (our_payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4566         let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4567
4568         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4569
4570         let nodes_0_serialized = nodes[0].node.encode();
4571         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4572         get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
4573
4574         logger = test_utils::TestLogger::new();
4575         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4576         persister = test_utils::TestPersister::new();
4577         let keys_manager = &chanmon_cfgs[0].keys_manager;
4578         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4579         nodes[0].chain_monitor = &new_chain_monitor;
4580         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4581         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4582                 &mut chan_0_monitor_read, keys_manager).unwrap();
4583         assert!(chan_0_monitor_read.is_empty());
4584
4585         let mut nodes_0_read = &nodes_0_serialized[..];
4586         let (_, nodes_0_deserialized_tmp) = {
4587                 let mut channel_monitors = HashMap::new();
4588                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4589                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4590                         default_config: UserConfig::default(),
4591                         keys_manager,
4592                         fee_estimator: &fee_estimator,
4593                         chain_monitor: nodes[0].chain_monitor,
4594                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4595                         logger: &logger,
4596                         channel_monitors,
4597                 }).unwrap()
4598         };
4599         nodes_0_deserialized = nodes_0_deserialized_tmp;
4600         assert!(nodes_0_read.is_empty());
4601
4602         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4603         nodes[0].node = &nodes_0_deserialized;
4604         check_added_monitors!(nodes[0], 1);
4605
4606         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4607
4608         fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4609         claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
4610 }
4611
4612 #[test]
4613 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4614         // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4615         let chanmon_cfgs = create_chanmon_cfgs(4);
4616         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4617         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4618         let logger: test_utils::TestLogger;
4619         let fee_estimator: test_utils::TestFeeEstimator;
4620         let persister: test_utils::TestPersister;
4621         let new_chain_monitor: test_utils::TestChainMonitor;
4622         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4623         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4624         let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
4625         let chan_id_2 = create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known()).2;
4626         let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
4627
4628         let mut node_0_stale_monitors_serialized = Vec::new();
4629         for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4630                 let mut writer = test_utils::TestVecWriter(Vec::new());
4631                 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4632                 node_0_stale_monitors_serialized.push(writer.0);
4633         }
4634
4635         let (our_payment_preimage, _, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4636
4637         // Serialize the ChannelManager here, but the monitor we keep up-to-date
4638         let nodes_0_serialized = nodes[0].node.encode();
4639
4640         route_payment(&nodes[0], &[&nodes[3]], 1000000);
4641         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4642         nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4643         nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4644
4645         // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4646         // nodes[3])
4647         let mut node_0_monitors_serialized = Vec::new();
4648         for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4649                 let mut writer = test_utils::TestVecWriter(Vec::new());
4650                 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4651                 node_0_monitors_serialized.push(writer.0);
4652         }
4653
4654         logger = test_utils::TestLogger::new();
4655         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4656         persister = test_utils::TestPersister::new();
4657         let keys_manager = &chanmon_cfgs[0].keys_manager;
4658         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4659         nodes[0].chain_monitor = &new_chain_monitor;
4660
4661
4662         let mut node_0_stale_monitors = Vec::new();
4663         for serialized in node_0_stale_monitors_serialized.iter() {
4664                 let mut read = &serialized[..];
4665                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4666                 assert!(read.is_empty());
4667                 node_0_stale_monitors.push(monitor);
4668         }
4669
4670         let mut node_0_monitors = Vec::new();
4671         for serialized in node_0_monitors_serialized.iter() {
4672                 let mut read = &serialized[..];
4673                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4674                 assert!(read.is_empty());
4675                 node_0_monitors.push(monitor);
4676         }
4677
4678         let mut nodes_0_read = &nodes_0_serialized[..];
4679         if let Err(msgs::DecodeError::InvalidValue) =
4680                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4681                 default_config: UserConfig::default(),
4682                 keys_manager,
4683                 fee_estimator: &fee_estimator,
4684                 chain_monitor: nodes[0].chain_monitor,
4685                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4686                 logger: &logger,
4687                 channel_monitors: node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4688         }) { } else {
4689                 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4690         };
4691
4692         let mut nodes_0_read = &nodes_0_serialized[..];
4693         let (_, nodes_0_deserialized_tmp) =
4694                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4695                 default_config: UserConfig::default(),
4696                 keys_manager,
4697                 fee_estimator: &fee_estimator,
4698                 chain_monitor: nodes[0].chain_monitor,
4699                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4700                 logger: &logger,
4701                 channel_monitors: node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4702         }).unwrap();
4703         nodes_0_deserialized = nodes_0_deserialized_tmp;
4704         assert!(nodes_0_read.is_empty());
4705
4706         { // Channel close should result in a commitment tx
4707                 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4708                 assert_eq!(txn.len(), 1);
4709                 check_spends!(txn[0], funding_tx);
4710                 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4711         }
4712
4713         for monitor in node_0_monitors.drain(..) {
4714                 assert!(nodes[0].chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor).is_ok());
4715                 check_added_monitors!(nodes[0], 1);
4716         }
4717         nodes[0].node = &nodes_0_deserialized;
4718         check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
4719
4720         // nodes[1] and nodes[2] have no lost state with nodes[0]...
4721         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4722         reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4723         //... and we can even still claim the payment!
4724         claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage);
4725
4726         nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4727         let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4728         nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4729         nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4730         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4731         assert_eq!(msg_events.len(), 1);
4732         if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
4733                 match action {
4734                         &ErrorAction::SendErrorMessage { ref msg } => {
4735                                 assert_eq!(msg.channel_id, channel_id);
4736                         },
4737                         _ => panic!("Unexpected event!"),
4738                 }
4739         }
4740 }
4741
4742 macro_rules! check_spendable_outputs {
4743         ($node: expr, $keysinterface: expr) => {
4744                 {
4745                         let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4746                         let mut txn = Vec::new();
4747                         let mut all_outputs = Vec::new();
4748                         let secp_ctx = Secp256k1::new();
4749                         for event in events.drain(..) {
4750                                 match event {
4751                                         Event::SpendableOutputs { mut outputs } => {
4752                                                 for outp in outputs.drain(..) {
4753                                                         txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4754                                                         all_outputs.push(outp);
4755                                                 }
4756                                         },
4757                                         _ => panic!("Unexpected event"),
4758                                 };
4759                         }
4760                         if all_outputs.len() > 1 {
4761                                 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) {
4762                                         txn.push(tx);
4763                                 }
4764                         }
4765                         txn
4766                 }
4767         }
4768 }
4769
4770 #[test]
4771 fn test_claim_sizeable_push_msat() {
4772         // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4773         let chanmon_cfgs = create_chanmon_cfgs(2);
4774         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4775         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4776         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4777
4778         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000, InitFeatures::known(), InitFeatures::known());
4779         nodes[1].node.force_close_channel(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
4780         check_closed_broadcast!(nodes[1], true);
4781         check_added_monitors!(nodes[1], 1);
4782         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4783         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4784         assert_eq!(node_txn.len(), 1);
4785         check_spends!(node_txn[0], chan.3);
4786         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
4787
4788         mine_transaction(&nodes[1], &node_txn[0]);
4789         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4790
4791         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4792         assert_eq!(spend_txn.len(), 1);
4793         assert_eq!(spend_txn[0].input.len(), 1);
4794         check_spends!(spend_txn[0], node_txn[0]);
4795         assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
4796 }
4797
4798 #[test]
4799 fn test_claim_on_remote_sizeable_push_msat() {
4800         // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4801         // to_remote output is encumbered by a P2WPKH
4802         let chanmon_cfgs = create_chanmon_cfgs(2);
4803         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4804         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4805         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4806
4807         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000, InitFeatures::known(), InitFeatures::known());
4808         nodes[0].node.force_close_channel(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
4809         check_closed_broadcast!(nodes[0], true);
4810         check_added_monitors!(nodes[0], 1);
4811         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4812
4813         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4814         assert_eq!(node_txn.len(), 1);
4815         check_spends!(node_txn[0], chan.3);
4816         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
4817
4818         mine_transaction(&nodes[1], &node_txn[0]);
4819         check_closed_broadcast!(nodes[1], true);
4820         check_added_monitors!(nodes[1], 1);
4821         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4822         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4823
4824         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4825         assert_eq!(spend_txn.len(), 1);
4826         check_spends!(spend_txn[0], node_txn[0]);
4827 }
4828
4829 #[test]
4830 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4831         // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4832         // to_remote output is encumbered by a P2WPKH
4833
4834         let chanmon_cfgs = create_chanmon_cfgs(2);
4835         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4836         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4837         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4838
4839         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::known(), InitFeatures::known());
4840         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4841         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4842         assert_eq!(revoked_local_txn[0].input.len(), 1);
4843         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4844
4845         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4846         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4847         check_closed_broadcast!(nodes[1], true);
4848         check_added_monitors!(nodes[1], 1);
4849         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4850
4851         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4852         mine_transaction(&nodes[1], &node_txn[0]);
4853         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4854
4855         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4856         assert_eq!(spend_txn.len(), 3);
4857         check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4858         check_spends!(spend_txn[1], node_txn[0]);
4859         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4860 }
4861
4862 #[test]
4863 fn test_static_spendable_outputs_preimage_tx() {
4864         let chanmon_cfgs = create_chanmon_cfgs(2);
4865         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4866         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4867         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4868
4869         // Create some initial channels
4870         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4871
4872         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
4873
4874         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4875         assert_eq!(commitment_tx[0].input.len(), 1);
4876         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4877
4878         // Settle A's commitment tx on B's chain
4879         nodes[1].node.claim_funds(payment_preimage);
4880         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
4881         check_added_monitors!(nodes[1], 1);
4882         mine_transaction(&nodes[1], &commitment_tx[0]);
4883         check_added_monitors!(nodes[1], 1);
4884         let events = nodes[1].node.get_and_clear_pending_msg_events();
4885         match events[0] {
4886                 MessageSendEvent::UpdateHTLCs { .. } => {},
4887                 _ => panic!("Unexpected event"),
4888         }
4889         match events[1] {
4890                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4891                 _ => panic!("Unexepected event"),
4892         }
4893
4894         // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4895         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4896         assert_eq!(node_txn.len(), 3);
4897         check_spends!(node_txn[0], commitment_tx[0]);
4898         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4899         check_spends!(node_txn[1], chan_1.3);
4900         check_spends!(node_txn[2], node_txn[1]);
4901
4902         mine_transaction(&nodes[1], &node_txn[0]);
4903         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4904         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4905
4906         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4907         assert_eq!(spend_txn.len(), 1);
4908         check_spends!(spend_txn[0], node_txn[0]);
4909 }
4910
4911 #[test]
4912 fn test_static_spendable_outputs_timeout_tx() {
4913         let chanmon_cfgs = create_chanmon_cfgs(2);
4914         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4915         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4916         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4917
4918         // Create some initial channels
4919         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4920
4921         // Rebalance the network a bit by relaying one payment through all the channels ...
4922         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4923
4924         let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4925
4926         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4927         assert_eq!(commitment_tx[0].input.len(), 1);
4928         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4929
4930         // Settle A's commitment tx on B' chain
4931         mine_transaction(&nodes[1], &commitment_tx[0]);
4932         check_added_monitors!(nodes[1], 1);
4933         let events = nodes[1].node.get_and_clear_pending_msg_events();
4934         match events[0] {
4935                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4936                 _ => panic!("Unexpected event"),
4937         }
4938         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4939
4940         // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4941         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4942         assert_eq!(node_txn.len(), 2); // ChannelManager : 1 local commitent tx, ChannelMonitor: timeout tx
4943         check_spends!(node_txn[0], chan_1.3.clone());
4944         check_spends!(node_txn[1],  commitment_tx[0].clone());
4945         assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4946
4947         mine_transaction(&nodes[1], &node_txn[1]);
4948         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4949         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4950         expect_payment_failed!(nodes[1], our_payment_hash, true);
4951
4952         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4953         assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4954         check_spends!(spend_txn[0], commitment_tx[0]);
4955         check_spends!(spend_txn[1], node_txn[1]);
4956         check_spends!(spend_txn[2], node_txn[1], commitment_tx[0]); // All outputs
4957 }
4958
4959 #[test]
4960 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4961         let chanmon_cfgs = create_chanmon_cfgs(2);
4962         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4963         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4964         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4965
4966         // Create some initial channels
4967         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4968
4969         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4970         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4971         assert_eq!(revoked_local_txn[0].input.len(), 1);
4972         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4973
4974         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4975
4976         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4977         check_closed_broadcast!(nodes[1], true);
4978         check_added_monitors!(nodes[1], 1);
4979         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4980
4981         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4982         assert_eq!(node_txn.len(), 2);
4983         assert_eq!(node_txn[0].input.len(), 2);
4984         check_spends!(node_txn[0], revoked_local_txn[0]);
4985
4986         mine_transaction(&nodes[1], &node_txn[0]);
4987         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4988
4989         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4990         assert_eq!(spend_txn.len(), 1);
4991         check_spends!(spend_txn[0], node_txn[0]);
4992 }
4993
4994 #[test]
4995 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4996         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4997         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4998         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4999         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5000         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5001
5002         // Create some initial channels
5003         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5004
5005         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5006         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5007         assert_eq!(revoked_local_txn[0].input.len(), 1);
5008         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5009
5010         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
5011
5012         // A will generate HTLC-Timeout from revoked commitment tx
5013         mine_transaction(&nodes[0], &revoked_local_txn[0]);
5014         check_closed_broadcast!(nodes[0], true);
5015         check_added_monitors!(nodes[0], 1);
5016         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5017         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5018
5019         let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5020         assert_eq!(revoked_htlc_txn.len(), 2);
5021         check_spends!(revoked_htlc_txn[0], chan_1.3);
5022         assert_eq!(revoked_htlc_txn[1].input.len(), 1);
5023         assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5024         check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
5025         assert_ne!(revoked_htlc_txn[1].lock_time, 0); // HTLC-Timeout
5026
5027         // B will generate justice tx from A's revoked commitment/HTLC tx
5028         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5029         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[1].clone()] });
5030         check_closed_broadcast!(nodes[1], true);
5031         check_added_monitors!(nodes[1], 1);
5032         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5033
5034         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5035         assert_eq!(node_txn.len(), 3); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs, ChannelManager: local commitment tx
5036         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5037         // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
5038         // transactions next...
5039         assert_eq!(node_txn[0].input.len(), 3);
5040         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[1]);
5041
5042         assert_eq!(node_txn[1].input.len(), 2);
5043         check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[1]);
5044         if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[1].txid() {
5045                 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
5046         } else {
5047                 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[1].txid());
5048                 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[1].input[0].previous_output);
5049         }
5050
5051         assert_eq!(node_txn[2].input.len(), 1);
5052         check_spends!(node_txn[2], chan_1.3);
5053
5054         mine_transaction(&nodes[1], &node_txn[1]);
5055         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5056
5057         // Check B's ChannelMonitor was able to generate the right spendable output descriptor
5058         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5059         assert_eq!(spend_txn.len(), 1);
5060         assert_eq!(spend_txn[0].input.len(), 1);
5061         check_spends!(spend_txn[0], node_txn[1]);
5062 }
5063
5064 #[test]
5065 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
5066         let mut chanmon_cfgs = create_chanmon_cfgs(2);
5067         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
5068         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5069         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5070         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5071
5072         // Create some initial channels
5073         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5074
5075         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5076         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5077         assert_eq!(revoked_local_txn[0].input.len(), 1);
5078         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5079
5080         // The to-be-revoked commitment tx should have one HTLC and one to_remote output
5081         assert_eq!(revoked_local_txn[0].output.len(), 2);
5082
5083         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
5084
5085         // B will generate HTLC-Success from revoked commitment tx
5086         mine_transaction(&nodes[1], &revoked_local_txn[0]);
5087         check_closed_broadcast!(nodes[1], true);
5088         check_added_monitors!(nodes[1], 1);
5089         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5090         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5091
5092         assert_eq!(revoked_htlc_txn.len(), 2);
5093         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
5094         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5095         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
5096
5097         // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
5098         let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
5099         assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
5100
5101         // A will generate justice tx from B's revoked commitment/HTLC tx
5102         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5103         connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
5104         check_closed_broadcast!(nodes[0], true);
5105         check_added_monitors!(nodes[0], 1);
5106         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5107
5108         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5109         assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
5110
5111         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5112         // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
5113         // transactions next...
5114         assert_eq!(node_txn[0].input.len(), 2);
5115         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
5116         if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
5117                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5118         } else {
5119                 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
5120                 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5121         }
5122
5123         assert_eq!(node_txn[1].input.len(), 1);
5124         check_spends!(node_txn[1], revoked_htlc_txn[0]);
5125
5126         check_spends!(node_txn[2], chan_1.3);
5127
5128         mine_transaction(&nodes[0], &node_txn[1]);
5129         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5130
5131         // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
5132         // didn't try to generate any new transactions.
5133
5134         // Check A's ChannelMonitor was able to generate the right spendable output descriptor
5135         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5136         assert_eq!(spend_txn.len(), 3);
5137         assert_eq!(spend_txn[0].input.len(), 1);
5138         check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
5139         assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5140         check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
5141         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
5142 }
5143
5144 #[test]
5145 fn test_onchain_to_onchain_claim() {
5146         // Test that in case of channel closure, we detect the state of output and claim HTLC
5147         // on downstream peer's remote commitment tx.
5148         // First, have C claim an HTLC against its own latest commitment transaction.
5149         // Then, broadcast these to B, which should update the monitor downstream on the A<->B
5150         // channel.
5151         // Finally, check that B will claim the HTLC output if A's latest commitment transaction
5152         // gets broadcast.
5153
5154         let chanmon_cfgs = create_chanmon_cfgs(3);
5155         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5156         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5157         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5158
5159         // Create some initial channels
5160         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5161         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5162
5163         // Ensure all nodes are at the same height
5164         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5165         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5166         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5167         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5168
5169         // Rebalance the network a bit by relaying one payment through all the channels ...
5170         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5171         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5172
5173         let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
5174         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
5175         check_spends!(commitment_tx[0], chan_2.3);
5176         nodes[2].node.claim_funds(payment_preimage);
5177         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
5178         check_added_monitors!(nodes[2], 1);
5179         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5180         assert!(updates.update_add_htlcs.is_empty());
5181         assert!(updates.update_fail_htlcs.is_empty());
5182         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5183         assert!(updates.update_fail_malformed_htlcs.is_empty());
5184
5185         mine_transaction(&nodes[2], &commitment_tx[0]);
5186         check_closed_broadcast!(nodes[2], true);
5187         check_added_monitors!(nodes[2], 1);
5188         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5189
5190         let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
5191         assert_eq!(c_txn.len(), 3);
5192         assert_eq!(c_txn[0], c_txn[2]);
5193         assert_eq!(commitment_tx[0], c_txn[1]);
5194         check_spends!(c_txn[1], chan_2.3);
5195         check_spends!(c_txn[2], c_txn[1]);
5196         assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
5197         assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5198         assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5199         assert_eq!(c_txn[0].lock_time, 0); // Success tx
5200
5201         // 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
5202         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
5203         connect_block(&nodes[1], &Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]});
5204         check_added_monitors!(nodes[1], 1);
5205         let events = nodes[1].node.get_and_clear_pending_events();
5206         assert_eq!(events.len(), 2);
5207         match events[0] {
5208                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5209                 _ => panic!("Unexpected event"),
5210         }
5211         match events[1] {
5212                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
5213                         assert_eq!(fee_earned_msat, Some(1000));
5214                         assert_eq!(prev_channel_id, Some(chan_1.2));
5215                         assert_eq!(claim_from_onchain_tx, true);
5216                         assert_eq!(next_channel_id, Some(chan_2.2));
5217                 },
5218                 _ => panic!("Unexpected event"),
5219         }
5220         {
5221                 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5222                 // ChannelMonitor: claim tx
5223                 assert_eq!(b_txn.len(), 1);
5224                 check_spends!(b_txn[0], chan_2.3); // B local commitment tx, issued by ChannelManager
5225                 b_txn.clear();
5226         }
5227         check_added_monitors!(nodes[1], 1);
5228         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5229         assert_eq!(msg_events.len(), 3);
5230         match msg_events[0] {
5231                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5232                 _ => panic!("Unexpected event"),
5233         }
5234         match msg_events[1] {
5235                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
5236                 _ => panic!("Unexpected event"),
5237         }
5238         match msg_events[2] {
5239                 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, .. } } => {
5240                         assert!(update_add_htlcs.is_empty());
5241                         assert!(update_fail_htlcs.is_empty());
5242                         assert_eq!(update_fulfill_htlcs.len(), 1);
5243                         assert!(update_fail_malformed_htlcs.is_empty());
5244                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5245                 },
5246                 _ => panic!("Unexpected event"),
5247         };
5248         // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
5249         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5250         mine_transaction(&nodes[1], &commitment_tx[0]);
5251         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5252         let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5253         // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
5254         assert_eq!(b_txn.len(), 3);
5255         check_spends!(b_txn[1], chan_1.3);
5256         check_spends!(b_txn[2], b_txn[1]);
5257         check_spends!(b_txn[0], commitment_tx[0]);
5258         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5259         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5260         assert_eq!(b_txn[0].lock_time, 0); // Success tx
5261
5262         check_closed_broadcast!(nodes[1], true);
5263         check_added_monitors!(nodes[1], 1);
5264 }
5265
5266 #[test]
5267 fn test_duplicate_payment_hash_one_failure_one_success() {
5268         // Topology : A --> B --> C --> D
5269         // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5270         // Note that because C will refuse to generate two payment secrets for the same payment hash,
5271         // we forward one of the payments onwards to D.
5272         let chanmon_cfgs = create_chanmon_cfgs(4);
5273         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
5274         // When this test was written, the default base fee floated based on the HTLC count.
5275         // It is now fixed, so we simply set the fee to the expected value here.
5276         let mut config = test_default_channel_config();
5277         config.channel_options.forwarding_fee_base_msat = 196;
5278         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
5279                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5280         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
5281
5282         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5283         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5284         create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5285
5286         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5287         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5288         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5289         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5290         connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
5291
5292         let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 900_000);
5293
5294         let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200).unwrap();
5295         // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
5296         // script push size limit so that the below script length checks match
5297         // ACCEPTED_HTLC_SCRIPT_WEIGHT.
5298         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id())
5299                 .with_features(InvoiceFeatures::known());
5300         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 900000, TEST_FINAL_CLTV - 40);
5301         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 900000, duplicate_payment_hash, payment_secret);
5302
5303         let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5304         assert_eq!(commitment_txn[0].input.len(), 1);
5305         check_spends!(commitment_txn[0], chan_2.3);
5306
5307         mine_transaction(&nodes[1], &commitment_txn[0]);
5308         check_closed_broadcast!(nodes[1], true);
5309         check_added_monitors!(nodes[1], 1);
5310         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5311         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
5312
5313         let htlc_timeout_tx;
5314         { // Extract one of the two HTLC-Timeout transaction
5315                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5316                 // ChannelMonitor: timeout tx * 2-or-3, ChannelManager: local commitment tx
5317                 assert!(node_txn.len() == 4 || node_txn.len() == 3);
5318                 check_spends!(node_txn[0], chan_2.3);
5319
5320                 check_spends!(node_txn[1], commitment_txn[0]);
5321                 assert_eq!(node_txn[1].input.len(), 1);
5322
5323                 if node_txn.len() > 3 {
5324                         check_spends!(node_txn[2], commitment_txn[0]);
5325                         assert_eq!(node_txn[2].input.len(), 1);
5326                         assert_eq!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
5327
5328                         check_spends!(node_txn[3], commitment_txn[0]);
5329                         assert_ne!(node_txn[1].input[0].previous_output, node_txn[3].input[0].previous_output);
5330                 } else {
5331                         check_spends!(node_txn[2], commitment_txn[0]);
5332                         assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
5333                 }
5334
5335                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5336                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5337                 if node_txn.len() > 3 {
5338                         assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5339                 }
5340                 htlc_timeout_tx = node_txn[1].clone();
5341         }
5342
5343         nodes[2].node.claim_funds(our_payment_preimage);
5344         expect_payment_claimed!(nodes[2], duplicate_payment_hash, 900_000);
5345
5346         mine_transaction(&nodes[2], &commitment_txn[0]);
5347         check_added_monitors!(nodes[2], 2);
5348         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5349         let events = nodes[2].node.get_and_clear_pending_msg_events();
5350         match events[0] {
5351                 MessageSendEvent::UpdateHTLCs { .. } => {},
5352                 _ => panic!("Unexpected event"),
5353         }
5354         match events[1] {
5355                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5356                 _ => panic!("Unexepected event"),
5357         }
5358         let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5359         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)
5360         check_spends!(htlc_success_txn[0], commitment_txn[0]);
5361         check_spends!(htlc_success_txn[1], commitment_txn[0]);
5362         assert_eq!(htlc_success_txn[0].input.len(), 1);
5363         assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5364         assert_eq!(htlc_success_txn[1].input.len(), 1);
5365         assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5366         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
5367         assert_eq!(htlc_success_txn[2], commitment_txn[0]);
5368         assert_eq!(htlc_success_txn[3], htlc_success_txn[0]);
5369         assert_eq!(htlc_success_txn[4], htlc_success_txn[1]);
5370         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
5371
5372         mine_transaction(&nodes[1], &htlc_timeout_tx);
5373         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5374         expect_pending_htlcs_forwardable!(nodes[1]);
5375         let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5376         assert!(htlc_updates.update_add_htlcs.is_empty());
5377         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5378         let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
5379         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5380         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5381         check_added_monitors!(nodes[1], 1);
5382
5383         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5384         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5385         {
5386                 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5387         }
5388         expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
5389
5390         // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5391         // Note that the fee paid is effectively double as the HTLC value (including the nodes[1] fee
5392         // and nodes[2] fee) is rounded down and then claimed in full.
5393         mine_transaction(&nodes[1], &htlc_success_txn[0]);
5394         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196*2), true, true);
5395         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5396         assert!(updates.update_add_htlcs.is_empty());
5397         assert!(updates.update_fail_htlcs.is_empty());
5398         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5399         assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
5400         assert!(updates.update_fail_malformed_htlcs.is_empty());
5401         check_added_monitors!(nodes[1], 1);
5402
5403         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5404         commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5405
5406         let events = nodes[0].node.get_and_clear_pending_events();
5407         match events[0] {
5408                 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
5409                         assert_eq!(*payment_preimage, our_payment_preimage);
5410                         assert_eq!(*payment_hash, duplicate_payment_hash);
5411                 }
5412                 _ => panic!("Unexpected event"),
5413         }
5414 }
5415
5416 #[test]
5417 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5418         let chanmon_cfgs = create_chanmon_cfgs(2);
5419         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5420         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5421         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5422
5423         // Create some initial channels
5424         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5425
5426         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
5427         let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5428         assert_eq!(local_txn.len(), 1);
5429         assert_eq!(local_txn[0].input.len(), 1);
5430         check_spends!(local_txn[0], chan_1.3);
5431
5432         // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5433         nodes[1].node.claim_funds(payment_preimage);
5434         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
5435         check_added_monitors!(nodes[1], 1);
5436
5437         mine_transaction(&nodes[1], &local_txn[0]);
5438         check_added_monitors!(nodes[1], 1);
5439         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5440         let events = nodes[1].node.get_and_clear_pending_msg_events();
5441         match events[0] {
5442                 MessageSendEvent::UpdateHTLCs { .. } => {},
5443                 _ => panic!("Unexpected event"),
5444         }
5445         match events[1] {
5446                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5447                 _ => panic!("Unexepected event"),
5448         }
5449         let node_tx = {
5450                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5451                 assert_eq!(node_txn.len(), 3);
5452                 assert_eq!(node_txn[0], node_txn[2]);
5453                 assert_eq!(node_txn[1], local_txn[0]);
5454                 assert_eq!(node_txn[0].input.len(), 1);
5455                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5456                 check_spends!(node_txn[0], local_txn[0]);
5457                 node_txn[0].clone()
5458         };
5459
5460         mine_transaction(&nodes[1], &node_tx);
5461         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
5462
5463         // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5464         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5465         assert_eq!(spend_txn.len(), 1);
5466         assert_eq!(spend_txn[0].input.len(), 1);
5467         check_spends!(spend_txn[0], node_tx);
5468         assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5469 }
5470
5471 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5472         // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5473         // unrevoked commitment transaction.
5474         // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5475         // a remote RAA before they could be failed backwards (and combinations thereof).
5476         // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5477         // use the same payment hashes.
5478         // Thus, we use a six-node network:
5479         //
5480         // A \         / E
5481         //    - C - D -
5482         // B /         \ F
5483         // And test where C fails back to A/B when D announces its latest commitment transaction
5484         let chanmon_cfgs = create_chanmon_cfgs(6);
5485         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5486         // When this test was written, the default base fee floated based on the HTLC count.
5487         // It is now fixed, so we simply set the fee to the expected value here.
5488         let mut config = test_default_channel_config();
5489         config.channel_options.forwarding_fee_base_msat = 196;
5490         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
5491                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5492         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5493
5494         create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5495         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5496         let chan = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5497         create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
5498         create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
5499
5500         // Rebalance and check output sanity...
5501         send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
5502         send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
5503         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 2);
5504
5505         let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
5506         // 0th HTLC:
5507         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
5508         // 1st HTLC:
5509         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
5510         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5511         // 2nd HTLC:
5512         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
5513         // 3rd HTLC:
5514         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
5515         // 4th HTLC:
5516         let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5517         // 5th HTLC:
5518         let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5519         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5520         // 6th HTLC:
5521         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());
5522         // 7th HTLC:
5523         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());
5524
5525         // 8th HTLC:
5526         let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5527         // 9th HTLC:
5528         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5529         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
5530
5531         // 10th HTLC:
5532         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
5533         // 11th HTLC:
5534         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5535         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());
5536
5537         // Double-check that six of the new HTLC were added
5538         // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5539         // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5540         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2).len(), 1);
5541         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 8);
5542
5543         // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5544         // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5545         nodes[4].node.fail_htlc_backwards(&payment_hash_1);
5546         nodes[4].node.fail_htlc_backwards(&payment_hash_3);
5547         nodes[4].node.fail_htlc_backwards(&payment_hash_5);
5548         nodes[4].node.fail_htlc_backwards(&payment_hash_6);
5549         check_added_monitors!(nodes[4], 0);
5550         expect_pending_htlcs_forwardable!(nodes[4]);
5551         check_added_monitors!(nodes[4], 1);
5552
5553         let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5554         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5555         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5556         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5557         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5558         commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5559
5560         // Fail 3rd below-dust and 7th above-dust HTLCs
5561         nodes[5].node.fail_htlc_backwards(&payment_hash_2);
5562         nodes[5].node.fail_htlc_backwards(&payment_hash_4);
5563         check_added_monitors!(nodes[5], 0);
5564         expect_pending_htlcs_forwardable!(nodes[5]);
5565         check_added_monitors!(nodes[5], 1);
5566
5567         let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5568         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5569         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5570         commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5571
5572         let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5573
5574         expect_pending_htlcs_forwardable!(nodes[3]);
5575         check_added_monitors!(nodes[3], 1);
5576         let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5577         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5578         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5579         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5580         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5581         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5582         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5583         if deliver_last_raa {
5584                 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5585         } else {
5586                 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5587         }
5588
5589         // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5590         // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5591         // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5592         // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5593         //
5594         // We now broadcast the latest commitment transaction, which *should* result in failures for
5595         // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5596         // the non-broadcast above-dust HTLCs.
5597         //
5598         // Alternatively, we may broadcast the previous commitment transaction, which should only
5599         // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5600         let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5601
5602         if announce_latest {
5603                 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5604         } else {
5605                 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5606         }
5607         let events = nodes[2].node.get_and_clear_pending_events();
5608         let close_event = if deliver_last_raa {
5609                 assert_eq!(events.len(), 2);
5610                 events[1].clone()
5611         } else {
5612                 assert_eq!(events.len(), 1);
5613                 events[0].clone()
5614         };
5615         match close_event {
5616                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5617                 _ => panic!("Unexpected event"),
5618         }
5619
5620         connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5621         check_closed_broadcast!(nodes[2], true);
5622         if deliver_last_raa {
5623                 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5624         } else {
5625                 expect_pending_htlcs_forwardable!(nodes[2]);
5626         }
5627         check_added_monitors!(nodes[2], 3);
5628
5629         let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5630         assert_eq!(cs_msgs.len(), 2);
5631         let mut a_done = false;
5632         for msg in cs_msgs {
5633                 match msg {
5634                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5635                                 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5636                                 // should be failed-backwards here.
5637                                 let target = if *node_id == nodes[0].node.get_our_node_id() {
5638                                         // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5639                                         for htlc in &updates.update_fail_htlcs {
5640                                                 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 });
5641                                         }
5642                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5643                                         assert!(!a_done);
5644                                         a_done = true;
5645                                         &nodes[0]
5646                                 } else {
5647                                         // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5648                                         for htlc in &updates.update_fail_htlcs {
5649                                                 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5650                                         }
5651                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5652                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5653                                         &nodes[1]
5654                                 };
5655                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5656                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5657                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5658                                 if announce_latest {
5659                                         target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5660                                         if *node_id == nodes[0].node.get_our_node_id() {
5661                                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5662                                         }
5663                                 }
5664                                 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5665                         },
5666                         _ => panic!("Unexpected event"),
5667                 }
5668         }
5669
5670         let as_events = nodes[0].node.get_and_clear_pending_events();
5671         assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5672         let mut as_failds = HashSet::new();
5673         let mut as_updates = 0;
5674         for event in as_events.iter() {
5675                 if let &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5676                         assert!(as_failds.insert(*payment_hash));
5677                         if *payment_hash != payment_hash_2 {
5678                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5679                         } else {
5680                                 assert!(!rejected_by_dest);
5681                         }
5682                         if network_update.is_some() {
5683                                 as_updates += 1;
5684                         }
5685                 } else { panic!("Unexpected event"); }
5686         }
5687         assert!(as_failds.contains(&payment_hash_1));
5688         assert!(as_failds.contains(&payment_hash_2));
5689         if announce_latest {
5690                 assert!(as_failds.contains(&payment_hash_3));
5691                 assert!(as_failds.contains(&payment_hash_5));
5692         }
5693         assert!(as_failds.contains(&payment_hash_6));
5694
5695         let bs_events = nodes[1].node.get_and_clear_pending_events();
5696         assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5697         let mut bs_failds = HashSet::new();
5698         let mut bs_updates = 0;
5699         for event in bs_events.iter() {
5700                 if let &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5701                         assert!(bs_failds.insert(*payment_hash));
5702                         if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5703                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5704                         } else {
5705                                 assert!(!rejected_by_dest);
5706                         }
5707                         if network_update.is_some() {
5708                                 bs_updates += 1;
5709                         }
5710                 } else { panic!("Unexpected event"); }
5711         }
5712         assert!(bs_failds.contains(&payment_hash_1));
5713         assert!(bs_failds.contains(&payment_hash_2));
5714         if announce_latest {
5715                 assert!(bs_failds.contains(&payment_hash_4));
5716         }
5717         assert!(bs_failds.contains(&payment_hash_5));
5718
5719         // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5720         // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5721         // unknown-preimage-etc, B should have gotten 2. Thus, in the
5722         // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5723         assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5724         assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5725 }
5726
5727 #[test]
5728 fn test_fail_backwards_latest_remote_announce_a() {
5729         do_test_fail_backwards_unrevoked_remote_announce(false, true);
5730 }
5731
5732 #[test]
5733 fn test_fail_backwards_latest_remote_announce_b() {
5734         do_test_fail_backwards_unrevoked_remote_announce(true, true);
5735 }
5736
5737 #[test]
5738 fn test_fail_backwards_previous_remote_announce() {
5739         do_test_fail_backwards_unrevoked_remote_announce(false, false);
5740         // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5741         // tested for in test_commitment_revoked_fail_backward_exhaustive()
5742 }
5743
5744 #[test]
5745 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5746         let chanmon_cfgs = create_chanmon_cfgs(2);
5747         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5748         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5749         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5750
5751         // Create some initial channels
5752         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5753
5754         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5755         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5756         assert_eq!(local_txn[0].input.len(), 1);
5757         check_spends!(local_txn[0], chan_1.3);
5758
5759         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5760         mine_transaction(&nodes[0], &local_txn[0]);
5761         check_closed_broadcast!(nodes[0], true);
5762         check_added_monitors!(nodes[0], 1);
5763         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5764         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5765
5766         let htlc_timeout = {
5767                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5768                 assert_eq!(node_txn.len(), 2);
5769                 check_spends!(node_txn[0], chan_1.3);
5770                 assert_eq!(node_txn[1].input.len(), 1);
5771                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5772                 check_spends!(node_txn[1], local_txn[0]);
5773                 node_txn[1].clone()
5774         };
5775
5776         mine_transaction(&nodes[0], &htlc_timeout);
5777         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5778         expect_payment_failed!(nodes[0], our_payment_hash, true);
5779
5780         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5781         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5782         assert_eq!(spend_txn.len(), 3);
5783         check_spends!(spend_txn[0], local_txn[0]);
5784         assert_eq!(spend_txn[1].input.len(), 1);
5785         check_spends!(spend_txn[1], htlc_timeout);
5786         assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5787         assert_eq!(spend_txn[2].input.len(), 2);
5788         check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5789         assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5790                 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5791 }
5792
5793 #[test]
5794 fn test_key_derivation_params() {
5795         // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5796         // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5797         // let us re-derive the channel key set to then derive a delayed_payment_key.
5798
5799         let chanmon_cfgs = create_chanmon_cfgs(3);
5800
5801         // We manually create the node configuration to backup the seed.
5802         let seed = [42; 32];
5803         let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5804         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);
5805         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() };
5806         let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5807         node_cfgs.remove(0);
5808         node_cfgs.insert(0, node);
5809
5810         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5811         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5812
5813         // Create some initial channels
5814         // Create a dummy channel to advance index by one and thus test re-derivation correctness
5815         // for node 0
5816         let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5817         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5818         assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5819
5820         // Ensure all nodes are at the same height
5821         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5822         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5823         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5824         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5825
5826         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5827         let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5828         let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5829         assert_eq!(local_txn_1[0].input.len(), 1);
5830         check_spends!(local_txn_1[0], chan_1.3);
5831
5832         // We check funding pubkey are unique
5833         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]));
5834         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]));
5835         if from_0_funding_key_0 == from_1_funding_key_0
5836             || from_0_funding_key_0 == from_1_funding_key_1
5837             || from_0_funding_key_1 == from_1_funding_key_0
5838             || from_0_funding_key_1 == from_1_funding_key_1 {
5839                 panic!("Funding pubkeys aren't unique");
5840         }
5841
5842         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5843         mine_transaction(&nodes[0], &local_txn_1[0]);
5844         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5845         check_closed_broadcast!(nodes[0], true);
5846         check_added_monitors!(nodes[0], 1);
5847         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5848
5849         let htlc_timeout = {
5850                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5851                 assert_eq!(node_txn[1].input.len(), 1);
5852                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5853                 check_spends!(node_txn[1], local_txn_1[0]);
5854                 node_txn[1].clone()
5855         };
5856
5857         mine_transaction(&nodes[0], &htlc_timeout);
5858         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5859         expect_payment_failed!(nodes[0], our_payment_hash, true);
5860
5861         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5862         let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5863         let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5864         assert_eq!(spend_txn.len(), 3);
5865         check_spends!(spend_txn[0], local_txn_1[0]);
5866         assert_eq!(spend_txn[1].input.len(), 1);
5867         check_spends!(spend_txn[1], htlc_timeout);
5868         assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5869         assert_eq!(spend_txn[2].input.len(), 2);
5870         check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5871         assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5872                 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5873 }
5874
5875 #[test]
5876 fn test_static_output_closing_tx() {
5877         let chanmon_cfgs = create_chanmon_cfgs(2);
5878         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5879         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5880         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5881
5882         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5883
5884         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5885         let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5886
5887         mine_transaction(&nodes[0], &closing_tx);
5888         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5889         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5890
5891         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5892         assert_eq!(spend_txn.len(), 1);
5893         check_spends!(spend_txn[0], closing_tx);
5894
5895         mine_transaction(&nodes[1], &closing_tx);
5896         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5897         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5898
5899         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5900         assert_eq!(spend_txn.len(), 1);
5901         check_spends!(spend_txn[0], closing_tx);
5902 }
5903
5904 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5905         let chanmon_cfgs = create_chanmon_cfgs(2);
5906         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5907         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5908         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5909         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5910
5911         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3_000_000 });
5912
5913         // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5914         // present in B's local commitment transaction, but none of A's commitment transactions.
5915         nodes[1].node.claim_funds(payment_preimage);
5916         check_added_monitors!(nodes[1], 1);
5917         expect_payment_claimed!(nodes[1], payment_hash, if use_dust { 50000 } else { 3_000_000 });
5918
5919         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5920         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5921         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
5922
5923         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5924         check_added_monitors!(nodes[0], 1);
5925         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5926         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5927         check_added_monitors!(nodes[1], 1);
5928
5929         let starting_block = nodes[1].best_block_info();
5930         let mut block = Block {
5931                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5932                 txdata: vec![],
5933         };
5934         for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5935                 connect_block(&nodes[1], &block);
5936                 block.header.prev_blockhash = block.block_hash();
5937         }
5938         test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5939         check_closed_broadcast!(nodes[1], true);
5940         check_added_monitors!(nodes[1], 1);
5941         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5942 }
5943
5944 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5945         let chanmon_cfgs = create_chanmon_cfgs(2);
5946         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5947         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5948         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5949         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5950
5951         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5952         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
5953         check_added_monitors!(nodes[0], 1);
5954
5955         let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5956
5957         // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5958         // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5959         // to "time out" the HTLC.
5960
5961         let starting_block = nodes[1].best_block_info();
5962         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5963
5964         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5965                 connect_block(&nodes[0], &Block { header, txdata: Vec::new()});
5966                 header.prev_blockhash = header.block_hash();
5967         }
5968         test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5969         check_closed_broadcast!(nodes[0], true);
5970         check_added_monitors!(nodes[0], 1);
5971         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5972 }
5973
5974 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5975         let chanmon_cfgs = create_chanmon_cfgs(3);
5976         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5977         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5978         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5979         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5980
5981         // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5982         // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5983         // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5984         // actually revoked.
5985         let htlc_value = if use_dust { 50000 } else { 3000000 };
5986         let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5987         nodes[1].node.fail_htlc_backwards(&our_payment_hash);
5988         expect_pending_htlcs_forwardable!(nodes[1]);
5989         check_added_monitors!(nodes[1], 1);
5990
5991         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5992         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5993         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5994         check_added_monitors!(nodes[0], 1);
5995         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5996         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5997         check_added_monitors!(nodes[1], 1);
5998         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5999         check_added_monitors!(nodes[1], 1);
6000         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
6001
6002         if check_revoke_no_close {
6003                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
6004                 check_added_monitors!(nodes[0], 1);
6005         }
6006
6007         let starting_block = nodes[1].best_block_info();
6008         let mut block = Block {
6009                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
6010                 txdata: vec![],
6011         };
6012         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
6013                 connect_block(&nodes[0], &block);
6014                 block.header.prev_blockhash = block.block_hash();
6015         }
6016         if !check_revoke_no_close {
6017                 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
6018                 check_closed_broadcast!(nodes[0], true);
6019                 check_added_monitors!(nodes[0], 1);
6020                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6021         } else {
6022                 let events = nodes[0].node.get_and_clear_pending_events();
6023                 assert_eq!(events.len(), 2);
6024                 if let Event::PaymentPathFailed { ref payment_hash, .. } = events[0] {
6025                         assert_eq!(*payment_hash, our_payment_hash);
6026                 } else { panic!("Unexpected event"); }
6027                 if let Event::PaymentFailed { ref payment_hash, .. } = events[1] {
6028                         assert_eq!(*payment_hash, our_payment_hash);
6029                 } else { panic!("Unexpected event"); }
6030         }
6031 }
6032
6033 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
6034 // There are only a few cases to test here:
6035 //  * its not really normative behavior, but we test that below-dust HTLCs "included" in
6036 //    broadcastable commitment transactions result in channel closure,
6037 //  * its included in an unrevoked-but-previous remote commitment transaction,
6038 //  * its included in the latest remote or local commitment transactions.
6039 // We test each of the three possible commitment transactions individually and use both dust and
6040 // non-dust HTLCs.
6041 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
6042 // assume they are handled the same across all six cases, as both outbound and inbound failures are
6043 // tested for at least one of the cases in other tests.
6044 #[test]
6045 fn htlc_claim_single_commitment_only_a() {
6046         do_htlc_claim_local_commitment_only(true);
6047         do_htlc_claim_local_commitment_only(false);
6048
6049         do_htlc_claim_current_remote_commitment_only(true);
6050         do_htlc_claim_current_remote_commitment_only(false);
6051 }
6052
6053 #[test]
6054 fn htlc_claim_single_commitment_only_b() {
6055         do_htlc_claim_previous_remote_commitment_only(true, false);
6056         do_htlc_claim_previous_remote_commitment_only(false, false);
6057         do_htlc_claim_previous_remote_commitment_only(true, true);
6058         do_htlc_claim_previous_remote_commitment_only(false, true);
6059 }
6060
6061 #[test]
6062 #[should_panic]
6063 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
6064         let chanmon_cfgs = create_chanmon_cfgs(2);
6065         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6066         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6067         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6068         // Force duplicate randomness for every get-random call
6069         for node in nodes.iter() {
6070                 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
6071         }
6072
6073         // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
6074         let channel_value_satoshis=10000;
6075         let push_msat=10001;
6076         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
6077         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6078         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
6079         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
6080
6081         // Create a second channel with the same random values. This used to panic due to a colliding
6082         // channel_id, but now panics due to a colliding outbound SCID alias.
6083         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6084 }
6085
6086 #[test]
6087 fn bolt2_open_channel_sending_node_checks_part2() {
6088         let chanmon_cfgs = create_chanmon_cfgs(2);
6089         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6090         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6091         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6092
6093         // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
6094         let channel_value_satoshis=2^24;
6095         let push_msat=10001;
6096         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6097
6098         // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
6099         let channel_value_satoshis=10000;
6100         // Test when push_msat is equal to 1000 * funding_satoshis.
6101         let push_msat=1000*channel_value_satoshis+1;
6102         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6103
6104         // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
6105         let channel_value_satoshis=10000;
6106         let push_msat=10001;
6107         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
6108         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6109         assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
6110
6111         // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
6112         // 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
6113         assert!(node0_to_1_send_open_channel.channel_flags<=1);
6114
6115         // 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.
6116         assert!(BREAKDOWN_TIMEOUT>0);
6117         assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
6118
6119         // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
6120         let chain_hash=genesis_block(Network::Testnet).header.block_hash();
6121         assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
6122
6123         // 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.
6124         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
6125         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
6126         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
6127         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
6128         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
6129 }
6130
6131 #[test]
6132 fn bolt2_open_channel_sane_dust_limit() {
6133         let chanmon_cfgs = create_chanmon_cfgs(2);
6134         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6135         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6136         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6137
6138         let channel_value_satoshis=1000000;
6139         let push_msat=10001;
6140         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
6141         let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6142         node0_to_1_send_open_channel.dust_limit_satoshis = 547;
6143         node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
6144
6145         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
6146         let events = nodes[1].node.get_and_clear_pending_msg_events();
6147         let err_msg = match events[0] {
6148                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
6149                         msg.clone()
6150                 },
6151                 _ => panic!("Unexpected event"),
6152         };
6153         assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
6154 }
6155
6156 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
6157 // originated from our node, its failure is surfaced to the user. We trigger this failure to
6158 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
6159 // is no longer affordable once it's freed.
6160 #[test]
6161 fn test_fail_holding_cell_htlc_upon_free() {
6162         let chanmon_cfgs = create_chanmon_cfgs(2);
6163         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6164         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6165         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6166         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6167
6168         // First nodes[0] generates an update_fee, setting the channel's
6169         // pending_update_fee.
6170         {
6171                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6172                 *feerate_lock += 20;
6173         }
6174         nodes[0].node.timer_tick_occurred();
6175         check_added_monitors!(nodes[0], 1);
6176
6177         let events = nodes[0].node.get_and_clear_pending_msg_events();
6178         assert_eq!(events.len(), 1);
6179         let (update_msg, commitment_signed) = match events[0] {
6180                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6181                         (update_fee.as_ref(), commitment_signed)
6182                 },
6183                 _ => panic!("Unexpected event"),
6184         };
6185
6186         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6187
6188         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6189         let channel_reserve = chan_stat.channel_reserve_msat;
6190         let feerate = get_feerate!(nodes[0], chan.2);
6191         let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6192
6193         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6194         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6195         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6196
6197         // Send a payment which passes reserve checks but gets stuck in the holding cell.
6198         let our_payment_id = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6199         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6200         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6201
6202         // Flush the pending fee update.
6203         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6204         let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6205         check_added_monitors!(nodes[1], 1);
6206         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
6207         check_added_monitors!(nodes[0], 1);
6208
6209         // Upon receipt of the RAA, there will be an attempt to resend the holding cell
6210         // HTLC, but now that the fee has been raised the payment will now fail, causing
6211         // us to surface its failure to the user.
6212         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6213         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6214         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);
6215         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 {}",
6216                 hex::encode(our_payment_hash.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6217         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6218
6219         // Check that the payment failed to be sent out.
6220         let events = nodes[0].node.get_and_clear_pending_events();
6221         assert_eq!(events.len(), 1);
6222         match &events[0] {
6223                 &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, .. } => {
6224                         assert_eq!(our_payment_id, *payment_id.as_ref().unwrap());
6225                         assert_eq!(our_payment_hash.clone(), *payment_hash);
6226                         assert_eq!(*rejected_by_dest, false);
6227                         assert_eq!(*all_paths_failed, true);
6228                         assert_eq!(*network_update, None);
6229                         assert_eq!(*short_channel_id, None);
6230                         assert_eq!(*error_code, None);
6231                         assert_eq!(*error_data, None);
6232                 },
6233                 _ => panic!("Unexpected event"),
6234         }
6235 }
6236
6237 // Test that if multiple HTLCs are released from the holding cell and one is
6238 // valid but the other is no longer valid upon release, the valid HTLC can be
6239 // successfully completed while the other one fails as expected.
6240 #[test]
6241 fn test_free_and_fail_holding_cell_htlcs() {
6242         let chanmon_cfgs = create_chanmon_cfgs(2);
6243         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6244         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6245         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6246         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6247
6248         // First nodes[0] generates an update_fee, setting the channel's
6249         // pending_update_fee.
6250         {
6251                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6252                 *feerate_lock += 200;
6253         }
6254         nodes[0].node.timer_tick_occurred();
6255         check_added_monitors!(nodes[0], 1);
6256
6257         let events = nodes[0].node.get_and_clear_pending_msg_events();
6258         assert_eq!(events.len(), 1);
6259         let (update_msg, commitment_signed) = match events[0] {
6260                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6261                         (update_fee.as_ref(), commitment_signed)
6262                 },
6263                 _ => panic!("Unexpected event"),
6264         };
6265
6266         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6267
6268         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6269         let channel_reserve = chan_stat.channel_reserve_msat;
6270         let feerate = get_feerate!(nodes[0], chan.2);
6271         let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6272
6273         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6274         let amt_1 = 20000;
6275         let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors) - amt_1;
6276         let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
6277         let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
6278
6279         // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6280         nodes[0].node.send_payment(&route_1, payment_hash_1, &Some(payment_secret_1)).unwrap();
6281         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6282         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6283         let payment_id_2 = nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
6284         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6285         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6286
6287         // Flush the pending fee update.
6288         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6289         let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6290         check_added_monitors!(nodes[1], 1);
6291         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6292         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6293         check_added_monitors!(nodes[0], 2);
6294
6295         // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6296         // but now that the fee has been raised the second payment will now fail, causing us
6297         // to surface its failure to the user. The first payment should succeed.
6298         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6299         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6300         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);
6301         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 {}",
6302                 hex::encode(payment_hash_2.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6303         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6304
6305         // Check that the second payment failed to be sent out.
6306         let events = nodes[0].node.get_and_clear_pending_events();
6307         assert_eq!(events.len(), 1);
6308         match &events[0] {
6309                 &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, .. } => {
6310                         assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
6311                         assert_eq!(payment_hash_2.clone(), *payment_hash);
6312                         assert_eq!(*rejected_by_dest, false);
6313                         assert_eq!(*all_paths_failed, true);
6314                         assert_eq!(*network_update, None);
6315                         assert_eq!(*short_channel_id, None);
6316                         assert_eq!(*error_code, None);
6317                         assert_eq!(*error_data, None);
6318                 },
6319                 _ => panic!("Unexpected event"),
6320         }
6321
6322         // Complete the first payment and the RAA from the fee update.
6323         let (payment_event, send_raa_event) = {
6324                 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6325                 assert_eq!(msgs.len(), 2);
6326                 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6327         };
6328         let raa = match send_raa_event {
6329                 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6330                 _ => panic!("Unexpected event"),
6331         };
6332         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6333         check_added_monitors!(nodes[1], 1);
6334         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6335         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6336         let events = nodes[1].node.get_and_clear_pending_events();
6337         assert_eq!(events.len(), 1);
6338         match events[0] {
6339                 Event::PendingHTLCsForwardable { .. } => {},
6340                 _ => panic!("Unexpected event"),
6341         }
6342         nodes[1].node.process_pending_htlc_forwards();
6343         let events = nodes[1].node.get_and_clear_pending_events();
6344         assert_eq!(events.len(), 1);
6345         match events[0] {
6346                 Event::PaymentReceived { .. } => {},
6347                 _ => panic!("Unexpected event"),
6348         }
6349         nodes[1].node.claim_funds(payment_preimage_1);
6350         check_added_monitors!(nodes[1], 1);
6351         expect_payment_claimed!(nodes[1], payment_hash_1, amt_1);
6352
6353         let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6354         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6355         commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6356         expect_payment_sent!(nodes[0], payment_preimage_1);
6357 }
6358
6359 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6360 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6361 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6362 // once it's freed.
6363 #[test]
6364 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6365         let chanmon_cfgs = create_chanmon_cfgs(3);
6366         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6367         // When this test was written, the default base fee floated based on the HTLC count.
6368         // It is now fixed, so we simply set the fee to the expected value here.
6369         let mut config = test_default_channel_config();
6370         config.channel_options.forwarding_fee_base_msat = 196;
6371         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
6372         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6373         let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6374         let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6375
6376         // First nodes[1] generates an update_fee, setting the channel's
6377         // pending_update_fee.
6378         {
6379                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
6380                 *feerate_lock += 20;
6381         }
6382         nodes[1].node.timer_tick_occurred();
6383         check_added_monitors!(nodes[1], 1);
6384
6385         let events = nodes[1].node.get_and_clear_pending_msg_events();
6386         assert_eq!(events.len(), 1);
6387         let (update_msg, commitment_signed) = match events[0] {
6388                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6389                         (update_fee.as_ref(), commitment_signed)
6390                 },
6391                 _ => panic!("Unexpected event"),
6392         };
6393
6394         nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6395
6396         let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
6397         let channel_reserve = chan_stat.channel_reserve_msat;
6398         let feerate = get_feerate!(nodes[0], chan_0_1.2);
6399         let opt_anchors = get_opt_anchors!(nodes[0], chan_0_1.2);
6400
6401         // Send a payment which passes reserve checks but gets stuck in the holding cell.
6402         let feemsat = 239;
6403         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
6404         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors) - total_routing_fee_msat;
6405         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
6406         let payment_event = {
6407                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6408                 check_added_monitors!(nodes[0], 1);
6409
6410                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6411                 assert_eq!(events.len(), 1);
6412
6413                 SendEvent::from_event(events.remove(0))
6414         };
6415         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6416         check_added_monitors!(nodes[1], 0);
6417         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6418         expect_pending_htlcs_forwardable!(nodes[1]);
6419
6420         chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
6421         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6422
6423         // Flush the pending fee update.
6424         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6425         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6426         check_added_monitors!(nodes[2], 1);
6427         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6428         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6429         check_added_monitors!(nodes[1], 2);
6430
6431         // A final RAA message is generated to finalize the fee update.
6432         let events = nodes[1].node.get_and_clear_pending_msg_events();
6433         assert_eq!(events.len(), 1);
6434
6435         let raa_msg = match &events[0] {
6436                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6437                         msg.clone()
6438                 },
6439                 _ => panic!("Unexpected event"),
6440         };
6441
6442         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6443         check_added_monitors!(nodes[2], 1);
6444         assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6445
6446         // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6447         let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6448         assert_eq!(process_htlc_forwards_event.len(), 1);
6449         match &process_htlc_forwards_event[0] {
6450                 &Event::PendingHTLCsForwardable { .. } => {},
6451                 _ => panic!("Unexpected event"),
6452         }
6453
6454         // In response, we call ChannelManager's process_pending_htlc_forwards
6455         nodes[1].node.process_pending_htlc_forwards();
6456         check_added_monitors!(nodes[1], 1);
6457
6458         // This causes the HTLC to be failed backwards.
6459         let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6460         assert_eq!(fail_event.len(), 1);
6461         let (fail_msg, commitment_signed) = match &fail_event[0] {
6462                 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6463                         assert_eq!(updates.update_add_htlcs.len(), 0);
6464                         assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6465                         assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6466                         assert_eq!(updates.update_fail_htlcs.len(), 1);
6467                         (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6468                 },
6469                 _ => panic!("Unexpected event"),
6470         };
6471
6472         // Pass the failure messages back to nodes[0].
6473         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6474         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6475
6476         // Complete the HTLC failure+removal process.
6477         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6478         check_added_monitors!(nodes[0], 1);
6479         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6480         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6481         check_added_monitors!(nodes[1], 2);
6482         let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6483         assert_eq!(final_raa_event.len(), 1);
6484         let raa = match &final_raa_event[0] {
6485                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6486                 _ => panic!("Unexpected event"),
6487         };
6488         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6489         expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6490         check_added_monitors!(nodes[0], 1);
6491 }
6492
6493 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6494 // 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.
6495 //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.
6496
6497 #[test]
6498 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6499         //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6500         let chanmon_cfgs = create_chanmon_cfgs(2);
6501         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6502         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6503         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6504         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6505
6506         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6507         route.paths[0][0].fee_msat = 100;
6508
6509         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6510                 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6511         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6512         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6513 }
6514
6515 #[test]
6516 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6517         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6518         let chanmon_cfgs = create_chanmon_cfgs(2);
6519         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6520         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6521         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6522         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6523
6524         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6525         route.paths[0][0].fee_msat = 0;
6526         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6527                 assert_eq!(err, "Cannot send 0-msat HTLC"));
6528
6529         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6530         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6531 }
6532
6533 #[test]
6534 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6535         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6536         let chanmon_cfgs = create_chanmon_cfgs(2);
6537         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6538         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6539         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6540         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6541
6542         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6543         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6544         check_added_monitors!(nodes[0], 1);
6545         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6546         updates.update_add_htlcs[0].amount_msat = 0;
6547
6548         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6549         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6550         check_closed_broadcast!(nodes[1], true).unwrap();
6551         check_added_monitors!(nodes[1], 1);
6552         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
6553 }
6554
6555 #[test]
6556 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6557         //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6558         //It is enforced when constructing a route.
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
6565         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
6566                 .with_features(InvoiceFeatures::known());
6567         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000, 0);
6568         route.paths[0].last_mut().unwrap().cltv_expiry_delta = 500000001;
6569         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::RouteError { ref err },
6570                 assert_eq!(err, &"Channel CLTV overflowed?"));
6571 }
6572
6573 #[test]
6574 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6575         //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.
6576         //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6577         //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6578         let chanmon_cfgs = create_chanmon_cfgs(2);
6579         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6580         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6581         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6582         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6583         let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6584
6585         for i in 0..max_accepted_htlcs {
6586                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6587                 let payment_event = {
6588                         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6589                         check_added_monitors!(nodes[0], 1);
6590
6591                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6592                         assert_eq!(events.len(), 1);
6593                         if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6594                                 assert_eq!(htlcs[0].htlc_id, i);
6595                         } else {
6596                                 assert!(false);
6597                         }
6598                         SendEvent::from_event(events.remove(0))
6599                 };
6600                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6601                 check_added_monitors!(nodes[1], 0);
6602                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6603
6604                 expect_pending_htlcs_forwardable!(nodes[1]);
6605                 expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6606         }
6607         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6608         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6609                 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6610
6611         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6612         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6613 }
6614
6615 #[test]
6616 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6617         //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.
6618         let chanmon_cfgs = create_chanmon_cfgs(2);
6619         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6620         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6621         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6622         let channel_value = 100000;
6623         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::known(), InitFeatures::known());
6624         let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6625
6626         send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6627
6628         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6629         // Manually create a route over our max in flight (which our router normally automatically
6630         // limits us to.
6631         route.paths[0][0].fee_msat =  max_in_flight + 1;
6632         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6633                 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)));
6634
6635         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6636         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);
6637
6638         send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6639 }
6640
6641 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6642 #[test]
6643 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6644         //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6645         let chanmon_cfgs = create_chanmon_cfgs(2);
6646         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6647         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6648         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6649         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6650         let htlc_minimum_msat: u64;
6651         {
6652                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6653                 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6654                 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6655         }
6656
6657         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6658         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6659         check_added_monitors!(nodes[0], 1);
6660         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6661         updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6662         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6663         assert!(nodes[1].node.list_channels().is_empty());
6664         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6665         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()));
6666         check_added_monitors!(nodes[1], 1);
6667         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6668 }
6669
6670 #[test]
6671 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6672         //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
6673         let chanmon_cfgs = create_chanmon_cfgs(2);
6674         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6675         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6676         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6677         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6678
6679         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6680         let channel_reserve = chan_stat.channel_reserve_msat;
6681         let feerate = get_feerate!(nodes[0], chan.2);
6682         let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6683         // The 2* and +1 are for the fee spike reserve.
6684         let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6685
6686         let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6687         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6688         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6689         check_added_monitors!(nodes[0], 1);
6690         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6691
6692         // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6693         // at this time channel-initiatee receivers are not required to enforce that senders
6694         // respect the fee_spike_reserve.
6695         updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6696         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6697
6698         assert!(nodes[1].node.list_channels().is_empty());
6699         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6700         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6701         check_added_monitors!(nodes[1], 1);
6702         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6703 }
6704
6705 #[test]
6706 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6707         //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6708         //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6709         let chanmon_cfgs = create_chanmon_cfgs(2);
6710         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6711         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6712         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6713         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6714
6715         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3999999);
6716         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6717         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6718         let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6719         let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &Some(our_payment_secret), cur_height, &None).unwrap();
6720         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6721
6722         let mut msg = msgs::UpdateAddHTLC {
6723                 channel_id: chan.2,
6724                 htlc_id: 0,
6725                 amount_msat: 1000,
6726                 payment_hash: our_payment_hash,
6727                 cltv_expiry: htlc_cltv,
6728                 onion_routing_packet: onion_packet.clone(),
6729         };
6730
6731         for i in 0..super::channel::OUR_MAX_HTLCS {
6732                 msg.htlc_id = i as u64;
6733                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6734         }
6735         msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6736         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6737
6738         assert!(nodes[1].node.list_channels().is_empty());
6739         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6740         assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6741         check_added_monitors!(nodes[1], 1);
6742         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6743 }
6744
6745 #[test]
6746 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6747         //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6748         let chanmon_cfgs = create_chanmon_cfgs(2);
6749         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6750         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6751         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6752         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6753
6754         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6755         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6756         check_added_monitors!(nodes[0], 1);
6757         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6758         updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6759         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6760
6761         assert!(nodes[1].node.list_channels().is_empty());
6762         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6763         assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6764         check_added_monitors!(nodes[1], 1);
6765         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6766 }
6767
6768 #[test]
6769 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6770         //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6771         let chanmon_cfgs = create_chanmon_cfgs(2);
6772         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6773         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6774         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6775
6776         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6777         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6778         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6779         check_added_monitors!(nodes[0], 1);
6780         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6781         updates.update_add_htlcs[0].cltv_expiry = 500000000;
6782         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6783
6784         assert!(nodes[1].node.list_channels().is_empty());
6785         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6786         assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6787         check_added_monitors!(nodes[1], 1);
6788         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6789 }
6790
6791 #[test]
6792 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6793         //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6794         // We test this by first testing that that repeated HTLCs pass commitment signature checks
6795         // after disconnect and that non-sequential htlc_ids result in a channel failure.
6796         let chanmon_cfgs = create_chanmon_cfgs(2);
6797         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6798         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6799         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6800
6801         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6802         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6803         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6804         check_added_monitors!(nodes[0], 1);
6805         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6806         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6807
6808         //Disconnect and Reconnect
6809         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6810         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6811         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
6812         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6813         assert_eq!(reestablish_1.len(), 1);
6814         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
6815         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6816         assert_eq!(reestablish_2.len(), 1);
6817         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6818         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6819         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6820         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6821
6822         //Resend HTLC
6823         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6824         assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6825         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6826         check_added_monitors!(nodes[1], 1);
6827         let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6828
6829         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6830
6831         assert!(nodes[1].node.list_channels().is_empty());
6832         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6833         assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6834         check_added_monitors!(nodes[1], 1);
6835         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6836 }
6837
6838 #[test]
6839 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6840         //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.
6841
6842         let chanmon_cfgs = create_chanmon_cfgs(2);
6843         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6844         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6845         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6846         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6847         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6848         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6849
6850         check_added_monitors!(nodes[0], 1);
6851         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6852         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6853
6854         let update_msg = msgs::UpdateFulfillHTLC{
6855                 channel_id: chan.2,
6856                 htlc_id: 0,
6857                 payment_preimage: our_payment_preimage,
6858         };
6859
6860         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6861
6862         assert!(nodes[0].node.list_channels().is_empty());
6863         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6864         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()));
6865         check_added_monitors!(nodes[0], 1);
6866         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6867 }
6868
6869 #[test]
6870 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6871         //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.
6872
6873         let chanmon_cfgs = create_chanmon_cfgs(2);
6874         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6875         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6876         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6877         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6878
6879         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6880         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6881         check_added_monitors!(nodes[0], 1);
6882         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6883         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6884
6885         let update_msg = msgs::UpdateFailHTLC{
6886                 channel_id: chan.2,
6887                 htlc_id: 0,
6888                 reason: msgs::OnionErrorPacket { data: Vec::new()},
6889         };
6890
6891         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6892
6893         assert!(nodes[0].node.list_channels().is_empty());
6894         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6895         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()));
6896         check_added_monitors!(nodes[0], 1);
6897         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6898 }
6899
6900 #[test]
6901 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6902         //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.
6903
6904         let chanmon_cfgs = create_chanmon_cfgs(2);
6905         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6906         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6907         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6908         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6909
6910         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6911         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6912         check_added_monitors!(nodes[0], 1);
6913         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6914         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6915         let update_msg = msgs::UpdateFailMalformedHTLC{
6916                 channel_id: chan.2,
6917                 htlc_id: 0,
6918                 sha256_of_onion: [1; 32],
6919                 failure_code: 0x8000,
6920         };
6921
6922         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6923
6924         assert!(nodes[0].node.list_channels().is_empty());
6925         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6926         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()));
6927         check_added_monitors!(nodes[0], 1);
6928         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6929 }
6930
6931 #[test]
6932 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6933         //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6934
6935         let chanmon_cfgs = create_chanmon_cfgs(2);
6936         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6937         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6938         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6939         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6940
6941         let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6942
6943         nodes[1].node.claim_funds(our_payment_preimage);
6944         check_added_monitors!(nodes[1], 1);
6945         expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6946
6947         let events = nodes[1].node.get_and_clear_pending_msg_events();
6948         assert_eq!(events.len(), 1);
6949         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6950                 match events[0] {
6951                         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, .. } } => {
6952                                 assert!(update_add_htlcs.is_empty());
6953                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6954                                 assert!(update_fail_htlcs.is_empty());
6955                                 assert!(update_fail_malformed_htlcs.is_empty());
6956                                 assert!(update_fee.is_none());
6957                                 update_fulfill_htlcs[0].clone()
6958                         },
6959                         _ => panic!("Unexpected event"),
6960                 }
6961         };
6962
6963         update_fulfill_msg.htlc_id = 1;
6964
6965         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6966
6967         assert!(nodes[0].node.list_channels().is_empty());
6968         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6969         assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6970         check_added_monitors!(nodes[0], 1);
6971         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6972 }
6973
6974 #[test]
6975 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6976         //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.
6977
6978         let chanmon_cfgs = create_chanmon_cfgs(2);
6979         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6980         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6981         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6982         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6983
6984         let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6985
6986         nodes[1].node.claim_funds(our_payment_preimage);
6987         check_added_monitors!(nodes[1], 1);
6988         expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6989
6990         let events = nodes[1].node.get_and_clear_pending_msg_events();
6991         assert_eq!(events.len(), 1);
6992         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6993                 match events[0] {
6994                         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, .. } } => {
6995                                 assert!(update_add_htlcs.is_empty());
6996                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6997                                 assert!(update_fail_htlcs.is_empty());
6998                                 assert!(update_fail_malformed_htlcs.is_empty());
6999                                 assert!(update_fee.is_none());
7000                                 update_fulfill_htlcs[0].clone()
7001                         },
7002                         _ => panic!("Unexpected event"),
7003                 }
7004         };
7005
7006         update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
7007
7008         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
7009
7010         assert!(nodes[0].node.list_channels().is_empty());
7011         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
7012         assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
7013         check_added_monitors!(nodes[0], 1);
7014         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
7015 }
7016
7017 #[test]
7018 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
7019         //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.
7020
7021         let chanmon_cfgs = create_chanmon_cfgs(2);
7022         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7023         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7024         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7025         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7026
7027         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
7028         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7029         check_added_monitors!(nodes[0], 1);
7030
7031         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7032         updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
7033
7034         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
7035         check_added_monitors!(nodes[1], 0);
7036         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
7037
7038         let events = nodes[1].node.get_and_clear_pending_msg_events();
7039
7040         let mut update_msg: msgs::UpdateFailMalformedHTLC = {
7041                 match events[0] {
7042                         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, .. } } => {
7043                                 assert!(update_add_htlcs.is_empty());
7044                                 assert!(update_fulfill_htlcs.is_empty());
7045                                 assert!(update_fail_htlcs.is_empty());
7046                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
7047                                 assert!(update_fee.is_none());
7048                                 update_fail_malformed_htlcs[0].clone()
7049                         },
7050                         _ => panic!("Unexpected event"),
7051                 }
7052         };
7053         update_msg.failure_code &= !0x8000;
7054         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
7055
7056         assert!(nodes[0].node.list_channels().is_empty());
7057         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
7058         assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
7059         check_added_monitors!(nodes[0], 1);
7060         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
7061 }
7062
7063 #[test]
7064 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
7065         //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
7066         //    * 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.
7067
7068         let chanmon_cfgs = create_chanmon_cfgs(3);
7069         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7070         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7071         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7072         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7073         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7074
7075         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
7076
7077         //First hop
7078         let mut payment_event = {
7079                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7080                 check_added_monitors!(nodes[0], 1);
7081                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7082                 assert_eq!(events.len(), 1);
7083                 SendEvent::from_event(events.remove(0))
7084         };
7085         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7086         check_added_monitors!(nodes[1], 0);
7087         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7088         expect_pending_htlcs_forwardable!(nodes[1]);
7089         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7090         assert_eq!(events_2.len(), 1);
7091         check_added_monitors!(nodes[1], 1);
7092         payment_event = SendEvent::from_event(events_2.remove(0));
7093         assert_eq!(payment_event.msgs.len(), 1);
7094
7095         //Second Hop
7096         payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
7097         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
7098         check_added_monitors!(nodes[2], 0);
7099         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
7100
7101         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
7102         assert_eq!(events_3.len(), 1);
7103         let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
7104                 match events_3[0] {
7105                         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 } } => {
7106                                 assert!(update_add_htlcs.is_empty());
7107                                 assert!(update_fulfill_htlcs.is_empty());
7108                                 assert!(update_fail_htlcs.is_empty());
7109                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
7110                                 assert!(update_fee.is_none());
7111                                 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
7112                         },
7113                         _ => panic!("Unexpected event"),
7114                 }
7115         };
7116
7117         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
7118
7119         check_added_monitors!(nodes[1], 0);
7120         commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
7121         expect_pending_htlcs_forwardable!(nodes[1]);
7122         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
7123         assert_eq!(events_4.len(), 1);
7124
7125         //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
7126         match events_4[0] {
7127                 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, .. } } => {
7128                         assert!(update_add_htlcs.is_empty());
7129                         assert!(update_fulfill_htlcs.is_empty());
7130                         assert_eq!(update_fail_htlcs.len(), 1);
7131                         assert!(update_fail_malformed_htlcs.is_empty());
7132                         assert!(update_fee.is_none());
7133                 },
7134                 _ => panic!("Unexpected event"),
7135         };
7136
7137         check_added_monitors!(nodes[1], 1);
7138 }
7139
7140 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
7141         // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
7142         // 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
7143         // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
7144
7145         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7146         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7147         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7148         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7149         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7150         let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7151
7152         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7153
7154         // We route 2 dust-HTLCs between A and B
7155         let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7156         let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7157         route_payment(&nodes[0], &[&nodes[1]], 1000000);
7158
7159         // Cache one local commitment tx as previous
7160         let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7161
7162         // Fail one HTLC to prune it in the will-be-latest-local commitment tx
7163         nodes[1].node.fail_htlc_backwards(&payment_hash_2);
7164         check_added_monitors!(nodes[1], 0);
7165         expect_pending_htlcs_forwardable!(nodes[1]);
7166         check_added_monitors!(nodes[1], 1);
7167
7168         let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7169         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
7170         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
7171         check_added_monitors!(nodes[0], 1);
7172
7173         // Cache one local commitment tx as lastest
7174         let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7175
7176         let events = nodes[0].node.get_and_clear_pending_msg_events();
7177         match events[0] {
7178                 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
7179                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7180                 },
7181                 _ => panic!("Unexpected event"),
7182         }
7183         match events[1] {
7184                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
7185                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7186                 },
7187                 _ => panic!("Unexpected event"),
7188         }
7189
7190         assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
7191         // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7192         if announce_latest {
7193                 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
7194         } else {
7195                 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
7196         }
7197
7198         check_closed_broadcast!(nodes[0], true);
7199         check_added_monitors!(nodes[0], 1);
7200         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7201
7202         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7203         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7204         let events = nodes[0].node.get_and_clear_pending_events();
7205         // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
7206         assert_eq!(events.len(), 2);
7207         let mut first_failed = false;
7208         for event in events {
7209                 match event {
7210                         Event::PaymentPathFailed { payment_hash, .. } => {
7211                                 if payment_hash == payment_hash_1 {
7212                                         assert!(!first_failed);
7213                                         first_failed = true;
7214                                 } else {
7215                                         assert_eq!(payment_hash, payment_hash_2);
7216                                 }
7217                         }
7218                         _ => panic!("Unexpected event"),
7219                 }
7220         }
7221 }
7222
7223 #[test]
7224 fn test_failure_delay_dust_htlc_local_commitment() {
7225         do_test_failure_delay_dust_htlc_local_commitment(true);
7226         do_test_failure_delay_dust_htlc_local_commitment(false);
7227 }
7228
7229 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7230         // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7231         // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7232         // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7233         // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7234         // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7235         // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7236
7237         let chanmon_cfgs = create_chanmon_cfgs(3);
7238         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7239         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7240         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7241         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7242
7243         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7244
7245         let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7246         let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7247
7248         let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7249         let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7250
7251         // We revoked bs_commitment_tx
7252         if revoked {
7253                 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7254                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
7255         }
7256
7257         let mut timeout_tx = Vec::new();
7258         if local {
7259                 // We fail dust-HTLC 1 by broadcast of local commitment tx
7260                 mine_transaction(&nodes[0], &as_commitment_tx[0]);
7261                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7262                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7263                 expect_payment_failed!(nodes[0], dust_hash, true);
7264
7265                 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
7266                 check_closed_broadcast!(nodes[0], true);
7267                 check_added_monitors!(nodes[0], 1);
7268                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7269                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
7270                 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7271                 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7272                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7273                 mine_transaction(&nodes[0], &timeout_tx[0]);
7274                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7275                 expect_payment_failed!(nodes[0], non_dust_hash, true);
7276         } else {
7277                 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7278                 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
7279                 check_closed_broadcast!(nodes[0], true);
7280                 check_added_monitors!(nodes[0], 1);
7281                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7282                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7283                 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7284                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
7285                 if !revoked {
7286                         expect_payment_failed!(nodes[0], dust_hash, true);
7287                         assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7288                         // We fail non-dust-HTLC 2 by broadcast of local timeout tx on remote commitment tx
7289                         mine_transaction(&nodes[0], &timeout_tx[0]);
7290                         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7291                         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7292                         expect_payment_failed!(nodes[0], non_dust_hash, true);
7293                 } else {
7294                         // If revoked, both dust & non-dust HTLCs should have been failed after ANTI_REORG_DELAY confs of revoked
7295                         // commitment tx
7296                         let events = nodes[0].node.get_and_clear_pending_events();
7297                         assert_eq!(events.len(), 2);
7298                         let first;
7299                         match events[0] {
7300                                 Event::PaymentPathFailed { payment_hash, .. } => {
7301                                         if payment_hash == dust_hash { first = true; }
7302                                         else { first = false; }
7303                                 },
7304                                 _ => panic!("Unexpected event"),
7305                         }
7306                         match events[1] {
7307                                 Event::PaymentPathFailed { payment_hash, .. } => {
7308                                         if first { assert_eq!(payment_hash, non_dust_hash); }
7309                                         else { assert_eq!(payment_hash, dust_hash); }
7310                                 },
7311                                 _ => panic!("Unexpected event"),
7312                         }
7313                 }
7314         }
7315 }
7316
7317 #[test]
7318 fn test_sweep_outbound_htlc_failure_update() {
7319         do_test_sweep_outbound_htlc_failure_update(false, true);
7320         do_test_sweep_outbound_htlc_failure_update(false, false);
7321         do_test_sweep_outbound_htlc_failure_update(true, false);
7322 }
7323
7324 #[test]
7325 fn test_user_configurable_csv_delay() {
7326         // We test our channel constructors yield errors when we pass them absurd csv delay
7327
7328         let mut low_our_to_self_config = UserConfig::default();
7329         low_our_to_self_config.own_channel_config.our_to_self_delay = 6;
7330         let mut high_their_to_self_config = UserConfig::default();
7331         high_their_to_self_config.peer_channel_config_limits.their_to_self_delay = 100;
7332         let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7333         let chanmon_cfgs = create_chanmon_cfgs(2);
7334         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7335         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7336         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7337
7338         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7339         if let Err(error) = Channel::new_outbound(&&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) },
7340                 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), 1000000, 1000000, 0,
7341                 &low_our_to_self_config, 0, 42)
7342         {
7343                 match error {
7344                         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())); },
7345                         _ => panic!("Unexpected event"),
7346                 }
7347         } else { assert!(false) }
7348
7349         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7350         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7351         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7352         open_channel.to_self_delay = 200;
7353         if let Err(error) = Channel::new_from_req(&&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) },
7354                 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), &open_channel, 0,
7355                 &low_our_to_self_config, 0, &nodes[0].logger, 42)
7356         {
7357                 match error {
7358                         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()));  },
7359                         _ => panic!("Unexpected event"),
7360                 }
7361         } else { assert!(false); }
7362
7363         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7364         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7365         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()));
7366         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7367         accept_channel.to_self_delay = 200;
7368         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7369         let reason_msg;
7370         if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7371                 match action {
7372                         &ErrorAction::SendErrorMessage { ref msg } => {
7373                                 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()));
7374                                 reason_msg = msg.data.clone();
7375                         },
7376                         _ => { panic!(); }
7377                 }
7378         } else { panic!(); }
7379         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg });
7380
7381         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7382         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7383         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7384         open_channel.to_self_delay = 200;
7385         if let Err(error) = Channel::new_from_req(&&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) },
7386                 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), &open_channel, 0,
7387                 &high_their_to_self_config, 0, &nodes[0].logger, 42)
7388         {
7389                 match error {
7390                         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())); },
7391                         _ => panic!("Unexpected event"),
7392                 }
7393         } else { assert!(false); }
7394 }
7395
7396 #[test]
7397 fn test_data_loss_protect() {
7398         // We want to be sure that :
7399         // * we don't broadcast our Local Commitment Tx in case of fallen behind
7400         //   (but this is not quite true - we broadcast during Drop because chanmon is out of sync with chanmgr)
7401         // * we close channel in case of detecting other being fallen behind
7402         // * we are able to claim our own outputs thanks to to_remote being static
7403         // TODO: this test is incomplete and the data_loss_protect implementation is incomplete - see issue #775
7404         let persister;
7405         let logger;
7406         let fee_estimator;
7407         let tx_broadcaster;
7408         let chain_source;
7409         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7410         // We broadcast during Drop because chanmon is out of sync with chanmgr, which would cause a panic
7411         // during signing due to revoked tx
7412         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7413         let keys_manager = &chanmon_cfgs[0].keys_manager;
7414         let monitor;
7415         let node_state_0;
7416         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7417         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7418         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7419
7420         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7421
7422         // Cache node A state before any channel update
7423         let previous_node_state = nodes[0].node.encode();
7424         let mut previous_chain_monitor_state = test_utils::TestVecWriter(Vec::new());
7425         get_monitor!(nodes[0], chan.2).write(&mut previous_chain_monitor_state).unwrap();
7426
7427         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7428         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7429
7430         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7431         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7432
7433         // Restore node A from previous state
7434         logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7435         let mut chain_monitor = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut io::Cursor::new(previous_chain_monitor_state.0), keys_manager).unwrap().1;
7436         chain_source = test_utils::TestChainSource::new(Network::Testnet);
7437         tx_broadcaster = test_utils::TestBroadcaster { txn_broadcasted: Mutex::new(Vec::new()), blocks: Arc::new(Mutex::new(Vec::new())) };
7438         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
7439         persister = test_utils::TestPersister::new();
7440         monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &tx_broadcaster, &logger, &fee_estimator, &persister, keys_manager);
7441         node_state_0 = {
7442                 let mut channel_monitors = HashMap::new();
7443                 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chain_monitor);
7444                 <(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 {
7445                         keys_manager: keys_manager,
7446                         fee_estimator: &fee_estimator,
7447                         chain_monitor: &monitor,
7448                         logger: &logger,
7449                         tx_broadcaster: &tx_broadcaster,
7450                         default_config: UserConfig::default(),
7451                         channel_monitors,
7452                 }).unwrap().1
7453         };
7454         nodes[0].node = &node_state_0;
7455         assert!(monitor.watch_channel(OutPoint { txid: chan.3.txid(), index: 0 }, chain_monitor).is_ok());
7456         nodes[0].chain_monitor = &monitor;
7457         nodes[0].chain_source = &chain_source;
7458
7459         check_added_monitors!(nodes[0], 1);
7460
7461         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7462         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7463
7464         let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7465
7466         // Check we don't broadcast any transactions following learning of per_commitment_point from B
7467         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7468         check_added_monitors!(nodes[0], 1);
7469
7470         {
7471                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7472                 assert_eq!(node_txn.len(), 0);
7473         }
7474
7475         let mut reestablish_1 = Vec::with_capacity(1);
7476         for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7477                 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
7478                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7479                         reestablish_1.push(msg.clone());
7480                 } else if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7481                 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7482                         match action {
7483                                 &ErrorAction::SendErrorMessage { ref msg } => {
7484                                         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");
7485                                 },
7486                                 _ => panic!("Unexpected event!"),
7487                         }
7488                 } else {
7489                         panic!("Unexpected event")
7490                 }
7491         }
7492
7493         // Check we close channel detecting A is fallen-behind
7494         // Check that we sent the warning message when we detected that A has fallen behind,
7495         // and give the possibility for A to recover from the warning.
7496         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7497         let warn_msg = "Peer attempted to reestablish channel with a very old local commitment transaction".to_owned();
7498         assert!(check_warn_msg!(nodes[1], nodes[0].node.get_our_node_id(), chan.2).contains(&warn_msg));
7499
7500         // Check A is able to claim to_remote output
7501         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7502         // The node B should not broadcast the transaction to force close the channel!
7503         assert!(node_txn.is_empty());
7504         // B should now detect that there is something wrong and should force close the channel.
7505         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";
7506         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: exp_err.to_string() });
7507
7508         // after the warning message sent by B, we should not able to
7509         // use the channel, or reconnect with success to the channel.
7510         assert!(nodes[0].node.list_usable_channels().is_empty());
7511         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7512         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7513         let retry_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7514
7515         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &retry_reestablish[0]);
7516         let mut err_msgs_0 = Vec::with_capacity(1);
7517         for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7518                 if let MessageSendEvent::HandleError { ref action, .. } = msg {
7519                         match action {
7520                                 &ErrorAction::SendErrorMessage { ref msg } => {
7521                                         assert_eq!(msg.data, "Failed to find corresponding channel");
7522                                         err_msgs_0.push(msg.clone());
7523                                 },
7524                                 _ => panic!("Unexpected event!"),
7525                         }
7526                 } else {
7527                         panic!("Unexpected event!");
7528                 }
7529         }
7530         assert_eq!(err_msgs_0.len(), 1);
7531         nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), &err_msgs_0[0]);
7532         assert!(nodes[1].node.list_usable_channels().is_empty());
7533         check_added_monitors!(nodes[1], 1);
7534         check_closed_event!(nodes[1], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "Failed to find corresponding channel".to_owned() });
7535         check_closed_broadcast!(nodes[1], false);
7536 }
7537
7538 #[test]
7539 fn test_check_htlc_underpaying() {
7540         // Send payment through A -> B but A is maliciously
7541         // sending a probe payment (i.e less than expected value0
7542         // to B, B should refuse payment.
7543
7544         let chanmon_cfgs = create_chanmon_cfgs(2);
7545         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7546         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7547         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7548
7549         // Create some initial channels
7550         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7551
7552         let scorer = test_utils::TestScorer::with_penalty(0);
7553         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7554         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7555         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();
7556         let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7557         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200).unwrap();
7558         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7559         check_added_monitors!(nodes[0], 1);
7560
7561         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7562         assert_eq!(events.len(), 1);
7563         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7564         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7565         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7566
7567         // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7568         // and then will wait a second random delay before failing the HTLC back:
7569         expect_pending_htlcs_forwardable!(nodes[1]);
7570         expect_pending_htlcs_forwardable!(nodes[1]);
7571
7572         // Node 3 is expecting payment of 100_000 but received 10_000,
7573         // it should fail htlc like we didn't know the preimage.
7574         nodes[1].node.process_pending_htlc_forwards();
7575
7576         let events = nodes[1].node.get_and_clear_pending_msg_events();
7577         assert_eq!(events.len(), 1);
7578         let (update_fail_htlc, commitment_signed) = match events[0] {
7579                 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 } } => {
7580                         assert!(update_add_htlcs.is_empty());
7581                         assert!(update_fulfill_htlcs.is_empty());
7582                         assert_eq!(update_fail_htlcs.len(), 1);
7583                         assert!(update_fail_malformed_htlcs.is_empty());
7584                         assert!(update_fee.is_none());
7585                         (update_fail_htlcs[0].clone(), commitment_signed)
7586                 },
7587                 _ => panic!("Unexpected event"),
7588         };
7589         check_added_monitors!(nodes[1], 1);
7590
7591         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7592         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7593
7594         // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7595         let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7596         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(CHAN_CONFIRM_DEPTH));
7597         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7598 }
7599
7600 #[test]
7601 fn test_announce_disable_channels() {
7602         // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7603         // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7604
7605         let chanmon_cfgs = create_chanmon_cfgs(2);
7606         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7607         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7608         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7609
7610         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7611         create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::known(), InitFeatures::known());
7612         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7613
7614         // Disconnect peers
7615         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7616         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7617
7618         nodes[0].node.timer_tick_occurred(); // Enabled -> DisabledStaged
7619         nodes[0].node.timer_tick_occurred(); // DisabledStaged -> Disabled
7620         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7621         assert_eq!(msg_events.len(), 3);
7622         let mut chans_disabled = HashMap::new();
7623         for e in msg_events {
7624                 match e {
7625                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7626                                 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7627                                 // Check that each channel gets updated exactly once
7628                                 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7629                                         panic!("Generated ChannelUpdate for wrong chan!");
7630                                 }
7631                         },
7632                         _ => panic!("Unexpected event"),
7633                 }
7634         }
7635         // Reconnect peers
7636         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7637         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7638         assert_eq!(reestablish_1.len(), 3);
7639         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7640         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7641         assert_eq!(reestablish_2.len(), 3);
7642
7643         // Reestablish chan_1
7644         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7645         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7646         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7647         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7648         // Reestablish chan_2
7649         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7650         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7651         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7652         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7653         // Reestablish chan_3
7654         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7655         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7656         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7657         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7658
7659         nodes[0].node.timer_tick_occurred();
7660         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7661         nodes[0].node.timer_tick_occurred();
7662         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7663         assert_eq!(msg_events.len(), 3);
7664         for e in msg_events {
7665                 match e {
7666                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7667                                 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7668                                 match chans_disabled.remove(&msg.contents.short_channel_id) {
7669                                         // Each update should have a higher timestamp than the previous one, replacing
7670                                         // the old one.
7671                                         Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7672                                         None => panic!("Generated ChannelUpdate for wrong chan!"),
7673                                 }
7674                         },
7675                         _ => panic!("Unexpected event"),
7676                 }
7677         }
7678         // Check that each channel gets updated exactly once
7679         assert!(chans_disabled.is_empty());
7680 }
7681
7682 #[test]
7683 fn test_bump_penalty_txn_on_revoked_commitment() {
7684         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7685         // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7686
7687         let chanmon_cfgs = create_chanmon_cfgs(2);
7688         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7689         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7690         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7691
7692         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7693
7694         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7695         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id())
7696                 .with_features(InvoiceFeatures::known());
7697         let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000, 30);
7698         send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7699
7700         let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7701         // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7702         assert_eq!(revoked_txn[0].output.len(), 4);
7703         assert_eq!(revoked_txn[0].input.len(), 1);
7704         assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7705         let revoked_txid = revoked_txn[0].txid();
7706
7707         let mut penalty_sum = 0;
7708         for outp in revoked_txn[0].output.iter() {
7709                 if outp.script_pubkey.is_v0_p2wsh() {
7710                         penalty_sum += outp.value;
7711                 }
7712         }
7713
7714         // Connect blocks to change height_timer range to see if we use right soonest_timelock
7715         let header_114 = connect_blocks(&nodes[1], 14);
7716
7717         // Actually revoke tx by claiming a HTLC
7718         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7719         let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7720         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] });
7721         check_added_monitors!(nodes[1], 1);
7722
7723         // One or more justice tx should have been broadcast, check it
7724         let penalty_1;
7725         let feerate_1;
7726         {
7727                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7728                 assert_eq!(node_txn.len(), 2); // justice tx (broadcasted from ChannelMonitor) + local commitment tx
7729                 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7730                 assert_eq!(node_txn[0].output.len(), 1);
7731                 check_spends!(node_txn[0], revoked_txn[0]);
7732                 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7733                 feerate_1 = fee_1 * 1000 / node_txn[0].weight() as u64;
7734                 penalty_1 = node_txn[0].txid();
7735                 node_txn.clear();
7736         };
7737
7738         // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7739         connect_blocks(&nodes[1], 15);
7740         let mut penalty_2 = penalty_1;
7741         let mut feerate_2 = 0;
7742         {
7743                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7744                 assert_eq!(node_txn.len(), 1);
7745                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7746                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7747                         assert_eq!(node_txn[0].output.len(), 1);
7748                         check_spends!(node_txn[0], revoked_txn[0]);
7749                         penalty_2 = node_txn[0].txid();
7750                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7751                         assert_ne!(penalty_2, penalty_1);
7752                         let fee_2 = penalty_sum - node_txn[0].output[0].value;
7753                         feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7754                         // Verify 25% bump heuristic
7755                         assert!(feerate_2 * 100 >= feerate_1 * 125);
7756                         node_txn.clear();
7757                 }
7758         }
7759         assert_ne!(feerate_2, 0);
7760
7761         // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7762         connect_blocks(&nodes[1], 1);
7763         let penalty_3;
7764         let mut feerate_3 = 0;
7765         {
7766                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7767                 assert_eq!(node_txn.len(), 1);
7768                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7769                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7770                         assert_eq!(node_txn[0].output.len(), 1);
7771                         check_spends!(node_txn[0], revoked_txn[0]);
7772                         penalty_3 = node_txn[0].txid();
7773                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7774                         assert_ne!(penalty_3, penalty_2);
7775                         let fee_3 = penalty_sum - node_txn[0].output[0].value;
7776                         feerate_3 = fee_3 * 1000 / node_txn[0].weight() as u64;
7777                         // Verify 25% bump heuristic
7778                         assert!(feerate_3 * 100 >= feerate_2 * 125);
7779                         node_txn.clear();
7780                 }
7781         }
7782         assert_ne!(feerate_3, 0);
7783
7784         nodes[1].node.get_and_clear_pending_events();
7785         nodes[1].node.get_and_clear_pending_msg_events();
7786 }
7787
7788 #[test]
7789 fn test_bump_penalty_txn_on_revoked_htlcs() {
7790         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7791         // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7792
7793         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7794         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7795         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7796         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7797         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7798
7799         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7800         // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7801         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7802         let scorer = test_utils::TestScorer::with_penalty(0);
7803         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7804         let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None,
7805                 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7806         let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7807         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7808         let route = get_route(&nodes[1].node.get_our_node_id(), &payment_params, &nodes[1].network_graph.read_only(), None,
7809                 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7810         send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7811
7812         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7813         assert_eq!(revoked_local_txn[0].input.len(), 1);
7814         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7815
7816         // Revoke local commitment tx
7817         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7818
7819         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7820         // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7821         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] });
7822         check_closed_broadcast!(nodes[1], true);
7823         check_added_monitors!(nodes[1], 1);
7824         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7825         connect_blocks(&nodes[1], 49); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7826
7827         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7828         assert_eq!(revoked_htlc_txn.len(), 3);
7829         check_spends!(revoked_htlc_txn[1], chan.3);
7830
7831         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7832         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7833         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7834
7835         assert_eq!(revoked_htlc_txn[2].input.len(), 1);
7836         assert_eq!(revoked_htlc_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7837         assert_eq!(revoked_htlc_txn[2].output.len(), 1);
7838         check_spends!(revoked_htlc_txn[2], revoked_local_txn[0]);
7839
7840         // Broadcast set of revoked txn on A
7841         let hash_128 = connect_blocks(&nodes[0], 40);
7842         let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7843         connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] });
7844         let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7845         connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[2].clone()] });
7846         let events = nodes[0].node.get_and_clear_pending_events();
7847         expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7848         match events[1] {
7849                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7850                 _ => panic!("Unexpected event"),
7851         }
7852         let first;
7853         let feerate_1;
7854         let penalty_txn;
7855         {
7856                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7857                 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7858                 // Verify claim tx are spending revoked HTLC txn
7859
7860                 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7861                 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7862                 // which are included in the same block (they are broadcasted because we scan the
7863                 // transactions linearly and generate claims as we go, they likely should be removed in the
7864                 // future).
7865                 assert_eq!(node_txn[0].input.len(), 1);
7866                 check_spends!(node_txn[0], revoked_local_txn[0]);
7867                 assert_eq!(node_txn[1].input.len(), 1);
7868                 check_spends!(node_txn[1], revoked_local_txn[0]);
7869                 assert_eq!(node_txn[2].input.len(), 1);
7870                 check_spends!(node_txn[2], revoked_local_txn[0]);
7871
7872                 // Each of the three justice transactions claim a separate (single) output of the three
7873                 // available, which we check here:
7874                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7875                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7876                 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7877
7878                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7879                 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7880
7881                 // node_txn[3] is the local commitment tx broadcast just because (and somewhat in case of
7882                 // reorgs, though its not clear its ever worth broadcasting conflicting txn like this when
7883                 // a remote commitment tx has already been confirmed).
7884                 check_spends!(node_txn[3], chan.3);
7885
7886                 // node_txn[4] spends the revoked outputs from the revoked_htlc_txn (which only have one
7887                 // output, checked above).
7888                 assert_eq!(node_txn[4].input.len(), 2);
7889                 assert_eq!(node_txn[4].output.len(), 1);
7890                 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7891
7892                 first = node_txn[4].txid();
7893                 // Store both feerates for later comparison
7894                 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[4].output[0].value;
7895                 feerate_1 = fee_1 * 1000 / node_txn[4].weight() as u64;
7896                 penalty_txn = vec![node_txn[2].clone()];
7897                 node_txn.clear();
7898         }
7899
7900         // Connect one more block to see if bumped penalty are issued for HTLC txn
7901         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7902         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7903         let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7904         connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() });
7905         {
7906                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7907                 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7908
7909                 check_spends!(node_txn[0], revoked_local_txn[0]);
7910                 check_spends!(node_txn[1], revoked_local_txn[0]);
7911                 // Note that these are both bogus - they spend outputs already claimed in block 129:
7912                 if node_txn[0].input[0].previous_output == revoked_htlc_txn[0].input[0].previous_output  {
7913                         assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7914                 } else {
7915                         assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7916                         assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7917                 }
7918
7919                 node_txn.clear();
7920         };
7921
7922         // Few more blocks to confirm penalty txn
7923         connect_blocks(&nodes[0], 4);
7924         assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7925         let header_144 = connect_blocks(&nodes[0], 9);
7926         let node_txn = {
7927                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7928                 assert_eq!(node_txn.len(), 1);
7929
7930                 assert_eq!(node_txn[0].input.len(), 2);
7931                 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7932                 // Verify bumped tx is different and 25% bump heuristic
7933                 assert_ne!(first, node_txn[0].txid());
7934                 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[0].output[0].value;
7935                 let feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7936                 assert!(feerate_2 * 100 > feerate_1 * 125);
7937                 let txn = vec![node_txn[0].clone()];
7938                 node_txn.clear();
7939                 txn
7940         };
7941         // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7942         let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7943         connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn });
7944         connect_blocks(&nodes[0], 20);
7945         {
7946                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7947                 // We verify than no new transaction has been broadcast because previously
7948                 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7949                 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7950                 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7951                 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7952                 // up bumped justice generation.
7953                 assert_eq!(node_txn.len(), 0);
7954                 node_txn.clear();
7955         }
7956         check_closed_broadcast!(nodes[0], true);
7957         check_added_monitors!(nodes[0], 1);
7958 }
7959
7960 #[test]
7961 fn test_bump_penalty_txn_on_remote_commitment() {
7962         // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7963         // we're able to claim outputs on remote commitment transaction before timelocks expiration
7964
7965         // Create 2 HTLCs
7966         // Provide preimage for one
7967         // Check aggregation
7968
7969         let chanmon_cfgs = create_chanmon_cfgs(2);
7970         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7971         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7972         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7973
7974         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7975         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
7976         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7977
7978         // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7979         let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7980         assert_eq!(remote_txn[0].output.len(), 4);
7981         assert_eq!(remote_txn[0].input.len(), 1);
7982         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7983
7984         // Claim a HTLC without revocation (provide B monitor with preimage)
7985         nodes[1].node.claim_funds(payment_preimage);
7986         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
7987         mine_transaction(&nodes[1], &remote_txn[0]);
7988         check_added_monitors!(nodes[1], 2);
7989         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7990
7991         // One or more claim tx should have been broadcast, check it
7992         let timeout;
7993         let preimage;
7994         let preimage_bump;
7995         let feerate_timeout;
7996         let feerate_preimage;
7997         {
7998                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7999                 // 9 transactions including:
8000                 // 1*2 ChannelManager local broadcasts of commitment + HTLC-Success
8001                 // 1*3 ChannelManager local broadcasts of commitment + HTLC-Success + HTLC-Timeout
8002                 // 2 * HTLC-Success (one RBF bump we'll check later)
8003                 // 1 * HTLC-Timeout
8004                 assert_eq!(node_txn.len(), 8);
8005                 assert_eq!(node_txn[0].input.len(), 1);
8006                 assert_eq!(node_txn[6].input.len(), 1);
8007                 check_spends!(node_txn[0], remote_txn[0]);
8008                 check_spends!(node_txn[6], remote_txn[0]);
8009
8010                 check_spends!(node_txn[1], chan.3);
8011                 check_spends!(node_txn[2], node_txn[1]);
8012
8013                 if node_txn[0].input[0].previous_output == node_txn[3].input[0].previous_output {
8014                         preimage_bump = node_txn[3].clone();
8015                         check_spends!(node_txn[3], remote_txn[0]);
8016
8017                         assert_eq!(node_txn[1], node_txn[4]);
8018                         assert_eq!(node_txn[2], node_txn[5]);
8019                 } else {
8020                         preimage_bump = node_txn[7].clone();
8021                         check_spends!(node_txn[7], remote_txn[0]);
8022                         assert_eq!(node_txn[0].input[0].previous_output, node_txn[7].input[0].previous_output);
8023
8024                         assert_eq!(node_txn[1], node_txn[3]);
8025                         assert_eq!(node_txn[2], node_txn[4]);
8026                 }
8027
8028                 timeout = node_txn[6].txid();
8029                 let index = node_txn[6].input[0].previous_output.vout;
8030                 let fee = remote_txn[0].output[index as usize].value - node_txn[6].output[0].value;
8031                 feerate_timeout = fee * 1000 / node_txn[6].weight() as u64;
8032
8033                 preimage = node_txn[0].txid();
8034                 let index = node_txn[0].input[0].previous_output.vout;
8035                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8036                 feerate_preimage = fee * 1000 / node_txn[0].weight() as u64;
8037
8038                 node_txn.clear();
8039         };
8040         assert_ne!(feerate_timeout, 0);
8041         assert_ne!(feerate_preimage, 0);
8042
8043         // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
8044         connect_blocks(&nodes[1], 15);
8045         {
8046                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8047                 assert_eq!(node_txn.len(), 1);
8048                 assert_eq!(node_txn[0].input.len(), 1);
8049                 assert_eq!(preimage_bump.input.len(), 1);
8050                 check_spends!(node_txn[0], remote_txn[0]);
8051                 check_spends!(preimage_bump, remote_txn[0]);
8052
8053                 let index = preimage_bump.input[0].previous_output.vout;
8054                 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
8055                 let new_feerate = fee * 1000 / preimage_bump.weight() as u64;
8056                 assert!(new_feerate * 100 > feerate_timeout * 125);
8057                 assert_ne!(timeout, preimage_bump.txid());
8058
8059                 let index = node_txn[0].input[0].previous_output.vout;
8060                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8061                 let new_feerate = fee * 1000 / node_txn[0].weight() as u64;
8062                 assert!(new_feerate * 100 > feerate_preimage * 125);
8063                 assert_ne!(preimage, node_txn[0].txid());
8064
8065                 node_txn.clear();
8066         }
8067
8068         nodes[1].node.get_and_clear_pending_events();
8069         nodes[1].node.get_and_clear_pending_msg_events();
8070 }
8071
8072 #[test]
8073 fn test_counterparty_raa_skip_no_crash() {
8074         // Previously, if our counterparty sent two RAAs in a row without us having provided a
8075         // commitment transaction, we would have happily carried on and provided them the next
8076         // commitment transaction based on one RAA forward. This would probably eventually have led to
8077         // channel closure, but it would not have resulted in funds loss. Still, our
8078         // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
8079         // check simply that the channel is closed in response to such an RAA, but don't check whether
8080         // we decide to punish our counterparty for revoking their funds (as we don't currently
8081         // implement that).
8082         let chanmon_cfgs = create_chanmon_cfgs(2);
8083         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8084         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8085         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8086         let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
8087
8088         let mut guard = nodes[0].node.channel_state.lock().unwrap();
8089         let keys = guard.by_id.get_mut(&channel_id).unwrap().get_signer();
8090
8091         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
8092
8093         // Make signer believe we got a counterparty signature, so that it allows the revocation
8094         keys.get_enforcement_state().last_holder_commitment -= 1;
8095         let per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
8096
8097         // Must revoke without gaps
8098         keys.get_enforcement_state().last_holder_commitment -= 1;
8099         keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
8100
8101         keys.get_enforcement_state().last_holder_commitment -= 1;
8102         let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
8103                 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
8104
8105         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
8106                 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
8107         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
8108         check_added_monitors!(nodes[1], 1);
8109         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
8110 }
8111
8112 #[test]
8113 fn test_bump_txn_sanitize_tracking_maps() {
8114         // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
8115         // verify we clean then right after expiration of ANTI_REORG_DELAY.
8116
8117         let chanmon_cfgs = create_chanmon_cfgs(2);
8118         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8119         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8120         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8121
8122         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8123         // Lock HTLC in both directions
8124         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8125         route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
8126
8127         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
8128         assert_eq!(revoked_local_txn[0].input.len(), 1);
8129         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8130
8131         // Revoke local commitment tx
8132         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
8133
8134         // Broadcast set of revoked txn on A
8135         connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
8136         expect_pending_htlcs_forwardable_ignore!(nodes[0]);
8137         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
8138
8139         mine_transaction(&nodes[0], &revoked_local_txn[0]);
8140         check_closed_broadcast!(nodes[0], true);
8141         check_added_monitors!(nodes[0], 1);
8142         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8143         let penalty_txn = {
8144                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8145                 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
8146                 check_spends!(node_txn[0], revoked_local_txn[0]);
8147                 check_spends!(node_txn[1], revoked_local_txn[0]);
8148                 check_spends!(node_txn[2], revoked_local_txn[0]);
8149                 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
8150                 node_txn.clear();
8151                 penalty_txn
8152         };
8153         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8154         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
8155         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8156         {
8157                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
8158                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
8159                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
8160         }
8161 }
8162
8163 #[test]
8164 fn test_pending_claimed_htlc_no_balance_underflow() {
8165         // Tests that if we have a pending outbound HTLC as well as a claimed-but-not-fully-removed
8166         // HTLC we will not underflow when we call `Channel::get_balance_msat()`.
8167         let chanmon_cfgs = create_chanmon_cfgs(2);
8168         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8169         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8170         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8171         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
8172
8173         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_010_000);
8174         nodes[1].node.claim_funds(payment_preimage);
8175         expect_payment_claimed!(nodes[1], payment_hash, 1_010_000);
8176         check_added_monitors!(nodes[1], 1);
8177         let fulfill_ev = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8178
8179         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &fulfill_ev.update_fulfill_htlcs[0]);
8180         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
8181         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &fulfill_ev.commitment_signed);
8182         check_added_monitors!(nodes[0], 1);
8183         let (_raa, _cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
8184
8185         // At this point nodes[1] has received 1,010k msat (10k msat more than their reserve) and can
8186         // send an HTLC back (though it will go in the holding cell). Send an HTLC back and check we
8187         // can get our balance.
8188
8189         // Get a route from nodes[1] to nodes[0] by getting a route going the other way and then flip
8190         // the public key of the only hop. This works around ChannelDetails not showing the
8191         // almost-claimed HTLC as available balance.
8192         let (mut route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 10_000);
8193         route.payment_params = None; // This is all wrong, but unnecessary
8194         route.paths[0][0].pubkey = nodes[0].node.get_our_node_id();
8195         let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[0]);
8196         nodes[1].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
8197
8198         assert_eq!(nodes[1].node.list_channels()[0].balance_msat, 1_000_000);
8199 }
8200
8201 #[test]
8202 fn test_channel_conf_timeout() {
8203         // Tests that, for inbound channels, we give up on them if the funding transaction does not
8204         // confirm within 2016 blocks, as recommended by BOLT 2.
8205         let chanmon_cfgs = create_chanmon_cfgs(2);
8206         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8207         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8208         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8209
8210         let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000, InitFeatures::known(), InitFeatures::known());
8211
8212         // The outbound node should wait forever for confirmation:
8213         // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
8214         // copied here instead of directly referencing the constant.
8215         connect_blocks(&nodes[0], 2016);
8216         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8217
8218         // The inbound node should fail the channel after exactly 2016 blocks
8219         connect_blocks(&nodes[1], 2015);
8220         check_added_monitors!(nodes[1], 0);
8221         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8222
8223         connect_blocks(&nodes[1], 1);
8224         check_added_monitors!(nodes[1], 1);
8225         check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut);
8226         let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
8227         assert_eq!(close_ev.len(), 1);
8228         match close_ev[0] {
8229                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
8230                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8231                         assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
8232                 },
8233                 _ => panic!("Unexpected event"),
8234         }
8235 }
8236
8237 #[test]
8238 fn test_override_channel_config() {
8239         let chanmon_cfgs = create_chanmon_cfgs(2);
8240         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8241         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8242         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8243
8244         // Node0 initiates a channel to node1 using the override config.
8245         let mut override_config = UserConfig::default();
8246         override_config.own_channel_config.our_to_self_delay = 200;
8247
8248         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
8249
8250         // Assert the channel created by node0 is using the override config.
8251         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8252         assert_eq!(res.channel_flags, 0);
8253         assert_eq!(res.to_self_delay, 200);
8254 }
8255
8256 #[test]
8257 fn test_override_0msat_htlc_minimum() {
8258         let mut zero_config = UserConfig::default();
8259         zero_config.own_channel_config.our_htlc_minimum_msat = 0;
8260         let chanmon_cfgs = create_chanmon_cfgs(2);
8261         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8262         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
8263         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8264
8265         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
8266         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8267         assert_eq!(res.htlc_minimum_msat, 1);
8268
8269         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8270         let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8271         assert_eq!(res.htlc_minimum_msat, 1);
8272 }
8273
8274 #[test]
8275 fn test_channel_update_has_correct_htlc_maximum_msat() {
8276         // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
8277         // Bolt 7 specifies that if present `htlc_maximum_msat`:
8278         // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
8279         // 90% of the `channel_value`.
8280         // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
8281
8282         let mut config_30_percent = UserConfig::default();
8283         config_30_percent.channel_options.announced_channel = true;
8284         config_30_percent.own_channel_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
8285         let mut config_50_percent = UserConfig::default();
8286         config_50_percent.channel_options.announced_channel = true;
8287         config_50_percent.own_channel_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
8288         let mut config_95_percent = UserConfig::default();
8289         config_95_percent.channel_options.announced_channel = true;
8290         config_95_percent.own_channel_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
8291         let mut config_100_percent = UserConfig::default();
8292         config_100_percent.channel_options.announced_channel = true;
8293         config_100_percent.own_channel_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
8294
8295         let chanmon_cfgs = create_chanmon_cfgs(4);
8296         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8297         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)]);
8298         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8299
8300         let channel_value_satoshis = 100000;
8301         let channel_value_msat = channel_value_satoshis * 1000;
8302         let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
8303         let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
8304         let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
8305
8306         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());
8307         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());
8308
8309         // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
8310         // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
8311         assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, OptionalField::Present(channel_value_50_percent_msat));
8312         // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
8313         // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
8314         assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, OptionalField::Present(channel_value_30_percent_msat));
8315
8316         // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
8317         // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
8318         // `channel_value`.
8319         assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, OptionalField::Present(channel_value_90_percent_msat));
8320         // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
8321         // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
8322         // `channel_value`.
8323         assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, OptionalField::Present(channel_value_90_percent_msat));
8324 }
8325
8326 #[test]
8327 fn test_manually_accept_inbound_channel_request() {
8328         let mut manually_accept_conf = UserConfig::default();
8329         manually_accept_conf.manually_accept_inbound_channels = true;
8330         let chanmon_cfgs = create_chanmon_cfgs(2);
8331         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8332         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8333         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8334
8335         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8336         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8337
8338         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8339
8340         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8341         // accepting the inbound channel request.
8342         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8343
8344         let events = nodes[1].node.get_and_clear_pending_events();
8345         match events[0] {
8346                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8347                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
8348                 }
8349                 _ => panic!("Unexpected event"),
8350         }
8351
8352         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8353         assert_eq!(accept_msg_ev.len(), 1);
8354
8355         match accept_msg_ev[0] {
8356                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8357                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8358                 }
8359                 _ => panic!("Unexpected event"),
8360         }
8361
8362         nodes[1].node.force_close_channel(&temp_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
8363
8364         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8365         assert_eq!(close_msg_ev.len(), 1);
8366
8367         let events = nodes[1].node.get_and_clear_pending_events();
8368         match events[0] {
8369                 Event::ChannelClosed { user_channel_id, .. } => {
8370                         assert_eq!(user_channel_id, 23);
8371                 }
8372                 _ => panic!("Unexpected event"),
8373         }
8374 }
8375
8376 #[test]
8377 fn test_manually_reject_inbound_channel_request() {
8378         let mut manually_accept_conf = UserConfig::default();
8379         manually_accept_conf.manually_accept_inbound_channels = true;
8380         let chanmon_cfgs = create_chanmon_cfgs(2);
8381         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8382         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8383         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8384
8385         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8386         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8387
8388         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8389
8390         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8391         // rejecting the inbound channel request.
8392         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8393
8394         let events = nodes[1].node.get_and_clear_pending_events();
8395         match events[0] {
8396                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8397                         nodes[1].node.force_close_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
8398                 }
8399                 _ => panic!("Unexpected event"),
8400         }
8401
8402         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8403         assert_eq!(close_msg_ev.len(), 1);
8404
8405         match close_msg_ev[0] {
8406                 MessageSendEvent::HandleError { ref node_id, .. } => {
8407                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8408                 }
8409                 _ => panic!("Unexpected event"),
8410         }
8411         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
8412 }
8413
8414 #[test]
8415 fn test_reject_funding_before_inbound_channel_accepted() {
8416         // This tests that when `UserConfig::manually_accept_inbound_channels` is set to true, inbound
8417         // channels must to be manually accepted through `ChannelManager::accept_inbound_channel` by
8418         // the node operator before the counterparty sends a `FundingCreated` message. If a
8419         // `FundingCreated` message is received before the channel is accepted, it should be rejected
8420         // and the channel should be closed.
8421         let mut manually_accept_conf = UserConfig::default();
8422         manually_accept_conf.manually_accept_inbound_channels = true;
8423         let chanmon_cfgs = create_chanmon_cfgs(2);
8424         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8425         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8426         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8427
8428         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8429         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8430         let temp_channel_id = res.temporary_channel_id;
8431
8432         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8433
8434         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in the `msg_events`.
8435         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8436
8437         // Clear the `Event::OpenChannelRequest` event without responding to the request.
8438         nodes[1].node.get_and_clear_pending_events();
8439
8440         // Get the `AcceptChannel` message of `nodes[1]` without calling
8441         // `ChannelManager::accept_inbound_channel`, which generates a
8442         // `MessageSendEvent::SendAcceptChannel` event. The message is passed to `nodes[0]`
8443         // `handle_accept_channel`, which is required in order for `create_funding_transaction` to
8444         // succeed when `nodes[0]` is passed to it.
8445         {
8446                 let mut lock;
8447                 let channel = get_channel_ref!(&nodes[1], lock, temp_channel_id);
8448                 let accept_chan_msg = channel.get_accept_channel_message();
8449                 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8450         }
8451
8452         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8453
8454         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8455         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8456
8457         // The `funding_created_msg` should be rejected by `nodes[1]` as it hasn't accepted the channel
8458         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8459
8460         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8461         assert_eq!(close_msg_ev.len(), 1);
8462
8463         let expected_err = "FundingCreated message received before the channel was accepted";
8464         match close_msg_ev[0] {
8465                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id, } => {
8466                         assert_eq!(msg.channel_id, temp_channel_id);
8467                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8468                         assert_eq!(msg.data, expected_err);
8469                 }
8470                 _ => panic!("Unexpected event"),
8471         }
8472
8473         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
8474 }
8475
8476 #[test]
8477 fn test_can_not_accept_inbound_channel_twice() {
8478         let mut manually_accept_conf = UserConfig::default();
8479         manually_accept_conf.manually_accept_inbound_channels = true;
8480         let chanmon_cfgs = create_chanmon_cfgs(2);
8481         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8482         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8483         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8484
8485         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8486         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8487
8488         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8489
8490         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8491         // accepting the inbound channel request.
8492         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8493
8494         let events = nodes[1].node.get_and_clear_pending_events();
8495         match events[0] {
8496                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8497                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
8498                         let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
8499                         match api_res {
8500                                 Err(APIError::APIMisuseError { err }) => {
8501                                         assert_eq!(err, "The channel isn't currently awaiting to be accepted.");
8502                                 },
8503                                 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
8504                                 Err(_) => panic!("Unexpected Error"),
8505                         }
8506                 }
8507                 _ => panic!("Unexpected event"),
8508         }
8509
8510         // Ensure that the channel wasn't closed after attempting to accept it twice.
8511         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8512         assert_eq!(accept_msg_ev.len(), 1);
8513
8514         match accept_msg_ev[0] {
8515                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8516                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8517                 }
8518                 _ => panic!("Unexpected event"),
8519         }
8520 }
8521
8522 #[test]
8523 fn test_can_not_accept_unknown_inbound_channel() {
8524         let chanmon_cfg = create_chanmon_cfgs(2);
8525         let node_cfg = create_node_cfgs(2, &chanmon_cfg);
8526         let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
8527         let nodes = create_network(2, &node_cfg, &node_chanmgr);
8528
8529         let unknown_channel_id = [0; 32];
8530         let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
8531         match api_res {
8532                 Err(APIError::ChannelUnavailable { err }) => {
8533                         assert_eq!(err, "Can't accept a channel that doesn't exist");
8534                 },
8535                 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
8536                 Err(_) => panic!("Unexpected Error"),
8537         }
8538 }
8539
8540 #[test]
8541 fn test_simple_mpp() {
8542         // Simple test of sending a multi-path payment.
8543         let chanmon_cfgs = create_chanmon_cfgs(4);
8544         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8545         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8546         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8547
8548         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8549         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8550         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8551         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8552
8553         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8554         let path = route.paths[0].clone();
8555         route.paths.push(path);
8556         route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8557         route.paths[0][0].short_channel_id = chan_1_id;
8558         route.paths[0][1].short_channel_id = chan_3_id;
8559         route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8560         route.paths[1][0].short_channel_id = chan_2_id;
8561         route.paths[1][1].short_channel_id = chan_4_id;
8562         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8563         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8564 }
8565
8566 #[test]
8567 fn test_preimage_storage() {
8568         // Simple test of payment preimage storage allowing no client-side storage to claim payments
8569         let chanmon_cfgs = create_chanmon_cfgs(2);
8570         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8571         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8572         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8573
8574         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8575
8576         {
8577                 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200).unwrap();
8578                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8579                 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8580                 check_added_monitors!(nodes[0], 1);
8581                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8582                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8583                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8584                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8585         }
8586         // Note that after leaving the above scope we have no knowledge of any arguments or return
8587         // values from previous calls.
8588         expect_pending_htlcs_forwardable!(nodes[1]);
8589         let events = nodes[1].node.get_and_clear_pending_events();
8590         assert_eq!(events.len(), 1);
8591         match events[0] {
8592                 Event::PaymentReceived { ref purpose, .. } => {
8593                         match &purpose {
8594                                 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
8595                                         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8596                                 },
8597                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
8598                         }
8599                 },
8600                 _ => panic!("Unexpected event"),
8601         }
8602 }
8603
8604 #[test]
8605 #[allow(deprecated)]
8606 fn test_secret_timeout() {
8607         // Simple test of payment secret storage time outs. After
8608         // `create_inbound_payment(_for_hash)_legacy` is removed, this test will be removed as well.
8609         let chanmon_cfgs = create_chanmon_cfgs(2);
8610         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8611         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8612         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8613
8614         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8615
8616         let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment_legacy(Some(100_000), 2).unwrap();
8617
8618         // We should fail to register the same payment hash twice, at least until we've connected a
8619         // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
8620         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8621                 assert_eq!(err, "Duplicate payment hash");
8622         } else { panic!(); }
8623         let mut block = {
8624                 let node_1_blocks = nodes[1].blocks.lock().unwrap();
8625                 Block {
8626                         header: BlockHeader {
8627                                 version: 0x2000000,
8628                                 prev_blockhash: node_1_blocks.last().unwrap().0.block_hash(),
8629                                 merkle_root: Default::default(),
8630                                 time: node_1_blocks.len() as u32 + 7200, bits: 42, nonce: 42 },
8631                         txdata: vec![],
8632                 }
8633         };
8634         connect_block(&nodes[1], &block);
8635         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8636                 assert_eq!(err, "Duplicate payment hash");
8637         } else { panic!(); }
8638
8639         // If we then connect the second block, we should be able to register the same payment hash
8640         // again (this time getting a new payment secret).
8641         block.header.prev_blockhash = block.header.block_hash();
8642         block.header.time += 1;
8643         connect_block(&nodes[1], &block);
8644         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2).unwrap();
8645         assert_ne!(payment_secret_1, our_payment_secret);
8646
8647         {
8648                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8649                 nodes[0].node.send_payment(&route, payment_hash, &Some(our_payment_secret)).unwrap();
8650                 check_added_monitors!(nodes[0], 1);
8651                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8652                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8653                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8654                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8655         }
8656         // Note that after leaving the above scope we have no knowledge of any arguments or return
8657         // values from previous calls.
8658         expect_pending_htlcs_forwardable!(nodes[1]);
8659         let events = nodes[1].node.get_and_clear_pending_events();
8660         assert_eq!(events.len(), 1);
8661         match events[0] {
8662                 Event::PaymentReceived { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret }, .. } => {
8663                         assert!(payment_preimage.is_none());
8664                         assert_eq!(payment_secret, our_payment_secret);
8665                         // We don't actually have the payment preimage with which to claim this payment!
8666                 },
8667                 _ => panic!("Unexpected event"),
8668         }
8669 }
8670
8671 #[test]
8672 fn test_bad_secret_hash() {
8673         // Simple test of unregistered payment hash/invalid payment secret handling
8674         let chanmon_cfgs = create_chanmon_cfgs(2);
8675         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8676         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8677         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8678
8679         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8680
8681         let random_payment_hash = PaymentHash([42; 32]);
8682         let random_payment_secret = PaymentSecret([43; 32]);
8683         let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2).unwrap();
8684         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8685
8686         // All the below cases should end up being handled exactly identically, so we macro the
8687         // resulting events.
8688         macro_rules! handle_unknown_invalid_payment_data {
8689                 () => {
8690                         check_added_monitors!(nodes[0], 1);
8691                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8692                         let payment_event = SendEvent::from_event(events.pop().unwrap());
8693                         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8694                         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8695
8696                         // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8697                         // again to process the pending backwards-failure of the HTLC
8698                         expect_pending_htlcs_forwardable!(nodes[1]);
8699                         expect_pending_htlcs_forwardable!(nodes[1]);
8700                         check_added_monitors!(nodes[1], 1);
8701
8702                         // We should fail the payment back
8703                         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8704                         match events.pop().unwrap() {
8705                                 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8706                                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8707                                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8708                                 },
8709                                 _ => panic!("Unexpected event"),
8710                         }
8711                 }
8712         }
8713
8714         let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8715         // Error data is the HTLC value (100,000) and current block height
8716         let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8717
8718         // Send a payment with the right payment hash but the wrong payment secret
8719         nodes[0].node.send_payment(&route, our_payment_hash, &Some(random_payment_secret)).unwrap();
8720         handle_unknown_invalid_payment_data!();
8721         expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8722
8723         // Send a payment with a random payment hash, but the right payment secret
8724         nodes[0].node.send_payment(&route, random_payment_hash, &Some(our_payment_secret)).unwrap();
8725         handle_unknown_invalid_payment_data!();
8726         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8727
8728         // Send a payment with a random payment hash and random payment secret
8729         nodes[0].node.send_payment(&route, random_payment_hash, &Some(random_payment_secret)).unwrap();
8730         handle_unknown_invalid_payment_data!();
8731         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8732 }
8733
8734 #[test]
8735 fn test_update_err_monitor_lockdown() {
8736         // Our monitor will lock update of local commitment transaction if a broadcastion condition
8737         // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8738         // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
8739         //
8740         // This scenario may happen in a watchtower setup, where watchtower process a block height
8741         // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8742         // commitment at same time.
8743
8744         let chanmon_cfgs = create_chanmon_cfgs(2);
8745         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8746         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8747         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8748
8749         // Create some initial channel
8750         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8751         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8752
8753         // Rebalance the network to generate htlc in the two directions
8754         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8755
8756         // Route a HTLC from node 0 to node 1 (but don't settle)
8757         let (preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
8758
8759         // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8760         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8761         let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8762         let persister = test_utils::TestPersister::new();
8763         let watchtower = {
8764                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8765                 let mut w = test_utils::TestVecWriter(Vec::new());
8766                 monitor.write(&mut w).unwrap();
8767                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8768                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8769                 assert!(new_monitor == *monitor);
8770                 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);
8771                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8772                 watchtower
8773         };
8774         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8775         let block = Block { header, txdata: vec![] };
8776         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8777         // transaction lock time requirements here.
8778         chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 0));
8779         watchtower.chain_monitor.block_connected(&block, 200);
8780
8781         // Try to update ChannelMonitor
8782         nodes[1].node.claim_funds(preimage);
8783         check_added_monitors!(nodes[1], 1);
8784         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
8785
8786         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8787         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8788         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8789         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8790                 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8791                         if let Err(_) =  watchtower.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8792                         if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8793                 } else { assert!(false); }
8794         } else { assert!(false); };
8795         // Our local monitor is in-sync and hasn't processed yet timeout
8796         check_added_monitors!(nodes[0], 1);
8797         let events = nodes[0].node.get_and_clear_pending_events();
8798         assert_eq!(events.len(), 1);
8799 }
8800
8801 #[test]
8802 fn test_concurrent_monitor_claim() {
8803         // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8804         // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8805         // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8806         // state N+1 confirms. Alice claims output from state N+1.
8807
8808         let chanmon_cfgs = create_chanmon_cfgs(2);
8809         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8810         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8811         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8812
8813         // Create some initial channel
8814         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8815         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8816
8817         // Rebalance the network to generate htlc in the two directions
8818         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8819
8820         // Route a HTLC from node 0 to node 1 (but don't settle)
8821         route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8822
8823         // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8824         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8825         let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8826         let persister = test_utils::TestPersister::new();
8827         let watchtower_alice = {
8828                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8829                 let mut w = test_utils::TestVecWriter(Vec::new());
8830                 monitor.write(&mut w).unwrap();
8831                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8832                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8833                 assert!(new_monitor == *monitor);
8834                 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);
8835                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8836                 watchtower
8837         };
8838         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8839         let block = Block { header, txdata: vec![] };
8840         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8841         // transaction lock time requirements here.
8842         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));
8843         watchtower_alice.chain_monitor.block_connected(&block, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8844
8845         // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8846         {
8847                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8848                 assert_eq!(txn.len(), 2);
8849                 txn.clear();
8850         }
8851
8852         // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8853         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8854         let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8855         let persister = test_utils::TestPersister::new();
8856         let watchtower_bob = {
8857                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8858                 let mut w = test_utils::TestVecWriter(Vec::new());
8859                 monitor.write(&mut w).unwrap();
8860                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8861                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8862                 assert!(new_monitor == *monitor);
8863                 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);
8864                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8865                 watchtower
8866         };
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 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8869
8870         // Route another payment to generate another update with still previous HTLC pending
8871         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8872         {
8873                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8874         }
8875         check_added_monitors!(nodes[1], 1);
8876
8877         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8878         assert_eq!(updates.update_add_htlcs.len(), 1);
8879         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8880         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8881                 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8882                         // Watchtower Alice should already have seen the block and reject the update
8883                         if let Err(_) =  watchtower_alice.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8884                         if let Ok(_) = watchtower_bob.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8885                         if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8886                 } else { assert!(false); }
8887         } else { assert!(false); };
8888         // Our local monitor is in-sync and hasn't processed yet timeout
8889         check_added_monitors!(nodes[0], 1);
8890
8891         //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8892         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8893         watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8894
8895         // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8896         let bob_state_y;
8897         {
8898                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8899                 assert_eq!(txn.len(), 2);
8900                 bob_state_y = txn[0].clone();
8901                 txn.clear();
8902         };
8903
8904         // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8905         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8906         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);
8907         {
8908                 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8909                 // We broadcast twice the transaction, once due to the HTLC-timeout, once due
8910                 // the onchain detection of the HTLC output
8911                 assert_eq!(htlc_txn.len(), 2);
8912                 check_spends!(htlc_txn[0], bob_state_y);
8913                 check_spends!(htlc_txn[1], bob_state_y);
8914         }
8915 }
8916
8917 #[test]
8918 fn test_pre_lockin_no_chan_closed_update() {
8919         // Test that if a peer closes a channel in response to a funding_created message we don't
8920         // generate a channel update (as the channel cannot appear on chain without a funding_signed
8921         // message).
8922         //
8923         // Doing so would imply a channel monitor update before the initial channel monitor
8924         // registration, violating our API guarantees.
8925         //
8926         // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8927         // then opening a second channel with the same funding output as the first (which is not
8928         // rejected because the first channel does not exist in the ChannelManager) and closing it
8929         // before receiving funding_signed.
8930         let chanmon_cfgs = create_chanmon_cfgs(2);
8931         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8932         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8933         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8934
8935         // Create an initial channel
8936         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8937         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8938         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8939         let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8940         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8941
8942         // Move the first channel through the funding flow...
8943         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8944
8945         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8946         check_added_monitors!(nodes[0], 0);
8947
8948         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8949         let channel_id = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8950         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8951         assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8952         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "Hi".to_string() }, true);
8953 }
8954
8955 #[test]
8956 fn test_htlc_no_detection() {
8957         // This test is a mutation to underscore the detection logic bug we had
8958         // before #653. HTLC value routed is above the remaining balance, thus
8959         // inverting HTLC and `to_remote` output. HTLC will come second and
8960         // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8961         // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8962         // outputs order detection for correct spending children filtring.
8963
8964         let chanmon_cfgs = create_chanmon_cfgs(2);
8965         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8966         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8967         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8968
8969         // Create some initial channels
8970         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8971
8972         send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8973         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8974         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8975         assert_eq!(local_txn[0].input.len(), 1);
8976         assert_eq!(local_txn[0].output.len(), 3);
8977         check_spends!(local_txn[0], chan_1.3);
8978
8979         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8980         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8981         connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] });
8982         // We deliberately connect the local tx twice as this should provoke a failure calling
8983         // this test before #653 fix.
8984         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);
8985         check_closed_broadcast!(nodes[0], true);
8986         check_added_monitors!(nodes[0], 1);
8987         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8988         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1);
8989
8990         let htlc_timeout = {
8991                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8992                 assert_eq!(node_txn[1].input.len(), 1);
8993                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8994                 check_spends!(node_txn[1], local_txn[0]);
8995                 node_txn[1].clone()
8996         };
8997
8998         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8999         connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] });
9000         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
9001         expect_payment_failed!(nodes[0], our_payment_hash, true);
9002 }
9003
9004 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
9005         // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
9006         // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
9007         // Carol, Alice would be the upstream node, and Carol the downstream.)
9008         //
9009         // Steps of the test:
9010         // 1) Alice sends a HTLC to Carol through Bob.
9011         // 2) Carol doesn't settle the HTLC.
9012         // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
9013         // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
9014         // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
9015         //    but can't be claimed as Bob doesn't have yet knowledge of the preimage.
9016         // 5) Carol release the preimage to Bob off-chain.
9017         // 6) Bob claims the offered output on the broadcasted commitment.
9018         let chanmon_cfgs = create_chanmon_cfgs(3);
9019         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9020         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9021         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9022
9023         // Create some initial channels
9024         let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9025         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9026
9027         // Steps (1) and (2):
9028         // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
9029         let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
9030
9031         // Check that Alice's commitment transaction now contains an output for this HTLC.
9032         let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
9033         check_spends!(alice_txn[0], chan_ab.3);
9034         assert_eq!(alice_txn[0].output.len(), 2);
9035         check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
9036         assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9037         assert_eq!(alice_txn.len(), 2);
9038
9039         // Steps (3) and (4):
9040         // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
9041         // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
9042         let mut force_closing_node = 0; // Alice force-closes
9043         let mut counterparty_node = 1; // Bob if Alice force-closes
9044
9045         // Bob force-closes
9046         if !broadcast_alice {
9047                 force_closing_node = 1;
9048                 counterparty_node = 0;
9049         }
9050         nodes[force_closing_node].node.force_close_channel(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id()).unwrap();
9051         check_closed_broadcast!(nodes[force_closing_node], true);
9052         check_added_monitors!(nodes[force_closing_node], 1);
9053         check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
9054         if go_onchain_before_fulfill {
9055                 let txn_to_broadcast = match broadcast_alice {
9056                         true => alice_txn.clone(),
9057                         false => get_local_commitment_txn!(nodes[1], chan_ab.2)
9058                 };
9059                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
9060                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
9061                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
9062                 if broadcast_alice {
9063                         check_closed_broadcast!(nodes[1], true);
9064                         check_added_monitors!(nodes[1], 1);
9065                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
9066                 }
9067                 assert_eq!(bob_txn.len(), 1);
9068                 check_spends!(bob_txn[0], chan_ab.3);
9069         }
9070
9071         // Step (5):
9072         // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
9073         // process of removing the HTLC from their commitment transactions.
9074         nodes[2].node.claim_funds(payment_preimage);
9075         check_added_monitors!(nodes[2], 1);
9076         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
9077
9078         let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
9079         assert!(carol_updates.update_add_htlcs.is_empty());
9080         assert!(carol_updates.update_fail_htlcs.is_empty());
9081         assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
9082         assert!(carol_updates.update_fee.is_none());
9083         assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
9084
9085         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
9086         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false, false);
9087         // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
9088         if !go_onchain_before_fulfill && broadcast_alice {
9089                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9090                 assert_eq!(events.len(), 1);
9091                 match events[0] {
9092                         MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
9093                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9094                         },
9095                         _ => panic!("Unexpected event"),
9096                 };
9097         }
9098         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
9099         // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
9100         // Carol<->Bob's updated commitment transaction info.
9101         check_added_monitors!(nodes[1], 2);
9102
9103         let events = nodes[1].node.get_and_clear_pending_msg_events();
9104         assert_eq!(events.len(), 2);
9105         let bob_revocation = match events[0] {
9106                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
9107                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
9108                         (*msg).clone()
9109                 },
9110                 _ => panic!("Unexpected event"),
9111         };
9112         let bob_updates = match events[1] {
9113                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
9114                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
9115                         (*updates).clone()
9116                 },
9117                 _ => panic!("Unexpected event"),
9118         };
9119
9120         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
9121         check_added_monitors!(nodes[2], 1);
9122         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
9123         check_added_monitors!(nodes[2], 1);
9124
9125         let events = nodes[2].node.get_and_clear_pending_msg_events();
9126         assert_eq!(events.len(), 1);
9127         let carol_revocation = match events[0] {
9128                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
9129                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
9130                         (*msg).clone()
9131                 },
9132                 _ => panic!("Unexpected event"),
9133         };
9134         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
9135         check_added_monitors!(nodes[1], 1);
9136
9137         // If this test requires the force-closed channel to not be on-chain until after the fulfill,
9138         // here's where we put said channel's commitment tx on-chain.
9139         let mut txn_to_broadcast = alice_txn.clone();
9140         if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
9141         if !go_onchain_before_fulfill {
9142                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
9143                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
9144                 // If Bob was the one to force-close, he will have already passed these checks earlier.
9145                 if broadcast_alice {
9146                         check_closed_broadcast!(nodes[1], true);
9147                         check_added_monitors!(nodes[1], 1);
9148                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
9149                 }
9150                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9151                 if broadcast_alice {
9152                         // In `connect_block()`, the ChainMonitor and ChannelManager are separately notified about a
9153                         // new block being connected. The ChannelManager being notified triggers a monitor update,
9154                         // which triggers broadcasting our commitment tx and an HTLC-claiming tx. The ChainMonitor
9155                         // being notified triggers the HTLC-claiming tx redundantly, resulting in 3 total txs being
9156                         // broadcasted.
9157                         assert_eq!(bob_txn.len(), 3);
9158                         check_spends!(bob_txn[1], chan_ab.3);
9159                 } else {
9160                         assert_eq!(bob_txn.len(), 2);
9161                         check_spends!(bob_txn[0], chan_ab.3);
9162                 }
9163         }
9164
9165         // Step (6):
9166         // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
9167         // broadcasted commitment transaction.
9168         {
9169                 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
9170                 if go_onchain_before_fulfill {
9171                         // Bob should now have an extra broadcasted tx, for the preimage-claiming transaction.
9172                         assert_eq!(bob_txn.len(), 2);
9173                 }
9174                 let script_weight = match broadcast_alice {
9175                         true => OFFERED_HTLC_SCRIPT_WEIGHT,
9176                         false => ACCEPTED_HTLC_SCRIPT_WEIGHT
9177                 };
9178                 // If Alice force-closed and Bob didn't receive her commitment transaction until after he
9179                 // received Carol's fulfill, he broadcasts the HTLC-output-claiming transaction first. Else if
9180                 // Bob force closed or if he found out about Alice's commitment tx before receiving Carol's
9181                 // fulfill, then he broadcasts the HTLC-output-claiming transaction second.
9182                 if broadcast_alice && !go_onchain_before_fulfill {
9183                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
9184                         assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
9185                 } else {
9186                         check_spends!(bob_txn[1], txn_to_broadcast[0]);
9187                         assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
9188                 }
9189         }
9190 }
9191
9192 #[test]
9193 fn test_onchain_htlc_settlement_after_close() {
9194         do_test_onchain_htlc_settlement_after_close(true, true);
9195         do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
9196         do_test_onchain_htlc_settlement_after_close(true, false);
9197         do_test_onchain_htlc_settlement_after_close(false, false);
9198 }
9199
9200 #[test]
9201 fn test_duplicate_chan_id() {
9202         // Test that if a given peer tries to open a channel with the same channel_id as one that is
9203         // already open we reject it and keep the old channel.
9204         //
9205         // Previously, full_stack_target managed to figure out that if you tried to open two channels
9206         // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
9207         // the existing channel when we detect the duplicate new channel, screwing up our monitor
9208         // updating logic for the existing channel.
9209         let chanmon_cfgs = create_chanmon_cfgs(2);
9210         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9211         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9212         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9213
9214         // Create an initial channel
9215         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9216         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9217         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9218         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()));
9219
9220         // Try to create a second channel with the same temporary_channel_id as the first and check
9221         // that it is rejected.
9222         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9223         {
9224                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9225                 assert_eq!(events.len(), 1);
9226                 match events[0] {
9227                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9228                                 // Technically, at this point, nodes[1] would be justified in thinking both the
9229                                 // first (valid) and second (invalid) channels are closed, given they both have
9230                                 // the same non-temporary channel_id. However, currently we do not, so we just
9231                                 // move forward with it.
9232                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9233                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9234                         },
9235                         _ => panic!("Unexpected event"),
9236                 }
9237         }
9238
9239         // Move the first channel through the funding flow...
9240         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
9241
9242         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9243         check_added_monitors!(nodes[0], 0);
9244
9245         let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9246         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
9247         {
9248                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
9249                 assert_eq!(added_monitors.len(), 1);
9250                 assert_eq!(added_monitors[0].0, funding_output);
9251                 added_monitors.clear();
9252         }
9253         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9254
9255         let funding_outpoint = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
9256         let channel_id = funding_outpoint.to_channel_id();
9257
9258         // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
9259         // temporary one).
9260
9261         // First try to open a second channel with a temporary channel id equal to the txid-based one.
9262         // Technically this is allowed by the spec, but we don't support it and there's little reason
9263         // to. Still, it shouldn't cause any other issues.
9264         open_chan_msg.temporary_channel_id = channel_id;
9265         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9266         {
9267                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9268                 assert_eq!(events.len(), 1);
9269                 match events[0] {
9270                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9271                                 // Technically, at this point, nodes[1] would be justified in thinking both
9272                                 // channels are closed, but currently we do not, so we just move forward with it.
9273                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9274                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9275                         },
9276                         _ => panic!("Unexpected event"),
9277                 }
9278         }
9279
9280         // Now try to create a second channel which has a duplicate funding output.
9281         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9282         let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9283         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_2_msg);
9284         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()));
9285         create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
9286
9287         let funding_created = {
9288                 let mut a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
9289                 // Once we call `get_outbound_funding_created` the channel has a duplicate channel_id as
9290                 // another channel in the ChannelManager - an invalid state. Thus, we'd panic later when we
9291                 // try to create another channel. Instead, we drop the channel entirely here (leaving the
9292                 // channelmanager in a possibly nonsense state instead).
9293                 let mut as_chan = a_channel_lock.by_id.remove(&open_chan_2_msg.temporary_channel_id).unwrap();
9294                 let logger = test_utils::TestLogger::new();
9295                 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
9296         };
9297         check_added_monitors!(nodes[0], 0);
9298         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
9299         // At this point we'll try to add a duplicate channel monitor, which will be rejected, but
9300         // still needs to be cleared here.
9301         check_added_monitors!(nodes[1], 1);
9302
9303         // ...still, nodes[1] will reject the duplicate channel.
9304         {
9305                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9306                 assert_eq!(events.len(), 1);
9307                 match events[0] {
9308                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9309                                 // Technically, at this point, nodes[1] would be justified in thinking both
9310                                 // channels are closed, but currently we do not, so we just move forward with it.
9311                                 assert_eq!(msg.channel_id, channel_id);
9312                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9313                         },
9314                         _ => panic!("Unexpected event"),
9315                 }
9316         }
9317
9318         // finally, finish creating the original channel and send a payment over it to make sure
9319         // everything is functional.
9320         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
9321         {
9322                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9323                 assert_eq!(added_monitors.len(), 1);
9324                 assert_eq!(added_monitors[0].0, funding_output);
9325                 added_monitors.clear();
9326         }
9327
9328         let events_4 = nodes[0].node.get_and_clear_pending_events();
9329         assert_eq!(events_4.len(), 0);
9330         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9331         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9332
9333         let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9334         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9335         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9336         send_payment(&nodes[0], &[&nodes[1]], 8000000);
9337 }
9338
9339 #[test]
9340 fn test_error_chans_closed() {
9341         // Test that we properly handle error messages, closing appropriate channels.
9342         //
9343         // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
9344         // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
9345         // we can test various edge cases around it to ensure we don't regress.
9346         let chanmon_cfgs = create_chanmon_cfgs(3);
9347         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9348         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9349         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9350
9351         // Create some initial channels
9352         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9353         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9354         let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9355
9356         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9357         assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
9358         assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
9359
9360         // Closing a channel from a different peer has no effect
9361         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
9362         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9363
9364         // Closing one channel doesn't impact others
9365         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
9366         check_added_monitors!(nodes[0], 1);
9367         check_closed_broadcast!(nodes[0], false);
9368         check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
9369         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
9370         assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
9371         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);
9372         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);
9373
9374         // A null channel ID should close all channels
9375         let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9376         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
9377         check_added_monitors!(nodes[0], 2);
9378         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
9379         let events = nodes[0].node.get_and_clear_pending_msg_events();
9380         assert_eq!(events.len(), 2);
9381         match events[0] {
9382                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9383                         assert_eq!(msg.contents.flags & 2, 2);
9384                 },
9385                 _ => panic!("Unexpected event"),
9386         }
9387         match events[1] {
9388                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9389                         assert_eq!(msg.contents.flags & 2, 2);
9390                 },
9391                 _ => panic!("Unexpected event"),
9392         }
9393         // Note that at this point users of a standard PeerHandler will end up calling
9394         // peer_disconnected with no_connection_possible set to false, duplicating the
9395         // close-all-channels logic. That's OK, we don't want to end up not force-closing channels for
9396         // users with their own peer handling logic. We duplicate the call here, however.
9397         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9398         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9399
9400         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
9401         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9402         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9403 }
9404
9405 #[test]
9406 fn test_invalid_funding_tx() {
9407         // Test that we properly handle invalid funding transactions sent to us from a peer.
9408         //
9409         // Previously, all other major lightning implementations had failed to properly sanitize
9410         // funding transactions from their counterparties, leading to a multi-implementation critical
9411         // security vulnerability (though we always sanitized properly, we've previously had
9412         // un-released crashes in the sanitization process).
9413         let chanmon_cfgs = create_chanmon_cfgs(2);
9414         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9415         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9416         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9417
9418         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
9419         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()));
9420         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()));
9421
9422         let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
9423         for output in tx.output.iter_mut() {
9424                 // Make the confirmed funding transaction have a bogus script_pubkey
9425                 output.script_pubkey = bitcoin::Script::new();
9426         }
9427
9428         nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
9429         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()));
9430         check_added_monitors!(nodes[1], 1);
9431
9432         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()));
9433         check_added_monitors!(nodes[0], 1);
9434
9435         let events_1 = nodes[0].node.get_and_clear_pending_events();
9436         assert_eq!(events_1.len(), 0);
9437
9438         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9439         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9440         nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9441
9442         let expected_err = "funding tx had wrong script/value or output index";
9443         confirm_transaction_at(&nodes[1], &tx, 1);
9444         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
9445         check_added_monitors!(nodes[1], 1);
9446         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9447         assert_eq!(events_2.len(), 1);
9448         if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9449                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9450                 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
9451                         assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
9452                 } else { panic!(); }
9453         } else { panic!(); }
9454         assert_eq!(nodes[1].node.list_channels().len(), 0);
9455 }
9456
9457 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9458         // In the first version of the chain::Confirm interface, after a refactor was made to not
9459         // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9460         // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9461         // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9462         // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9463         // spending transaction until height N+1 (or greater). This was due to the way
9464         // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9465         // spending transaction at the height the input transaction was confirmed at, not whether we
9466         // should broadcast a spending transaction at the current height.
9467         // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9468         // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9469         // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9470         // until we learned about an additional block.
9471         //
9472         // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9473         // aren't broadcasting transactions too early (ie not broadcasting them at all).
9474         let chanmon_cfgs = create_chanmon_cfgs(3);
9475         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9476         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9477         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9478         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9479
9480         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
9481         let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
9482         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9483         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
9484         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9485
9486         nodes[1].node.force_close_channel(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
9487         check_closed_broadcast!(nodes[1], true);
9488         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
9489         check_added_monitors!(nodes[1], 1);
9490         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9491         assert_eq!(node_txn.len(), 1);
9492
9493         let conf_height = nodes[1].best_block_info().1;
9494         if !test_height_before_timelock {
9495                 connect_blocks(&nodes[1], 24 * 6);
9496         }
9497         nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9498                 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9499         if test_height_before_timelock {
9500                 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9501                 // generate any events or broadcast any transactions
9502                 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9503                 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9504         } else {
9505                 // We should broadcast an HTLC transaction spending our funding transaction first
9506                 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9507                 assert_eq!(spending_txn.len(), 2);
9508                 assert_eq!(spending_txn[0], node_txn[0]);
9509                 check_spends!(spending_txn[1], node_txn[0]);
9510                 // We should also generate a SpendableOutputs event with the to_self output (as its
9511                 // timelock is up).
9512                 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9513                 assert_eq!(descriptor_spend_txn.len(), 1);
9514
9515                 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9516                 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9517                 // additional block built on top of the current chain.
9518                 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9519                         &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9520                 expect_pending_htlcs_forwardable!(nodes[1]);
9521                 check_added_monitors!(nodes[1], 1);
9522
9523                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9524                 assert!(updates.update_add_htlcs.is_empty());
9525                 assert!(updates.update_fulfill_htlcs.is_empty());
9526                 assert_eq!(updates.update_fail_htlcs.len(), 1);
9527                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9528                 assert!(updates.update_fee.is_none());
9529                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9530                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9531                 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9532         }
9533 }
9534
9535 #[test]
9536 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9537         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9538         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9539 }
9540
9541 #[test]
9542 fn test_forwardable_regen() {
9543         // Tests that if we reload a ChannelManager while forwards are pending we will regenerate the
9544         // PendingHTLCsForwardable event automatically, ensuring we don't forget to forward/receive
9545         // HTLCs.
9546         // We test it for both payment receipt and payment forwarding.
9547
9548         let chanmon_cfgs = create_chanmon_cfgs(3);
9549         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9550         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9551         let persister: test_utils::TestPersister;
9552         let new_chain_monitor: test_utils::TestChainMonitor;
9553         let nodes_1_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
9554         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9555         let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
9556         let chan_id_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known()).2;
9557
9558         // First send a payment to nodes[1]
9559         let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
9560         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
9561         check_added_monitors!(nodes[0], 1);
9562
9563         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9564         assert_eq!(events.len(), 1);
9565         let payment_event = SendEvent::from_event(events.pop().unwrap());
9566         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9567         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9568
9569         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9570
9571         // Next send a payment which is forwarded by nodes[1]
9572         let (route_2, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 200_000);
9573         nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
9574         check_added_monitors!(nodes[0], 1);
9575
9576         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9577         assert_eq!(events.len(), 1);
9578         let payment_event = SendEvent::from_event(events.pop().unwrap());
9579         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9580         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9581
9582         // There is already a PendingHTLCsForwardable event "pending" so another one will not be
9583         // generated
9584         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
9585
9586         // Now restart nodes[1] and make sure it regenerates a single PendingHTLCsForwardable
9587         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9588         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9589
9590         let nodes_1_serialized = nodes[1].node.encode();
9591         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9592         let mut chan_1_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9593         get_monitor!(nodes[1], chan_id_1).write(&mut chan_0_monitor_serialized).unwrap();
9594         get_monitor!(nodes[1], chan_id_2).write(&mut chan_1_monitor_serialized).unwrap();
9595
9596         persister = test_utils::TestPersister::new();
9597         let keys_manager = &chanmon_cfgs[1].keys_manager;
9598         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);
9599         nodes[1].chain_monitor = &new_chain_monitor;
9600
9601         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
9602         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9603                 &mut chan_0_monitor_read, keys_manager).unwrap();
9604         assert!(chan_0_monitor_read.is_empty());
9605         let mut chan_1_monitor_read = &chan_1_monitor_serialized.0[..];
9606         let (_, mut chan_1_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9607                 &mut chan_1_monitor_read, keys_manager).unwrap();
9608         assert!(chan_1_monitor_read.is_empty());
9609
9610         let mut nodes_1_read = &nodes_1_serialized[..];
9611         let (_, nodes_1_deserialized_tmp) = {
9612                 let mut channel_monitors = HashMap::new();
9613                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
9614                 channel_monitors.insert(chan_1_monitor.get_funding_txo().0, &mut chan_1_monitor);
9615                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_1_read, ChannelManagerReadArgs {
9616                         default_config: UserConfig::default(),
9617                         keys_manager,
9618                         fee_estimator: node_cfgs[1].fee_estimator,
9619                         chain_monitor: nodes[1].chain_monitor,
9620                         tx_broadcaster: nodes[1].tx_broadcaster.clone(),
9621                         logger: nodes[1].logger,
9622                         channel_monitors,
9623                 }).unwrap()
9624         };
9625         nodes_1_deserialized = nodes_1_deserialized_tmp;
9626         assert!(nodes_1_read.is_empty());
9627
9628         assert!(nodes[1].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
9629         assert!(nodes[1].chain_monitor.watch_channel(chan_1_monitor.get_funding_txo().0, chan_1_monitor).is_ok());
9630         nodes[1].node = &nodes_1_deserialized;
9631         check_added_monitors!(nodes[1], 2);
9632
9633         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9634         // Note that nodes[1] and nodes[2] resend their channel_ready here since they haven't updated
9635         // the commitment state.
9636         reconnect_nodes(&nodes[1], &nodes[2], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9637
9638         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
9639
9640         expect_pending_htlcs_forwardable!(nodes[1]);
9641         expect_payment_received!(nodes[1], payment_hash, payment_secret, 100_000);
9642         check_added_monitors!(nodes[1], 1);
9643
9644         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9645         assert_eq!(events.len(), 1);
9646         let payment_event = SendEvent::from_event(events.pop().unwrap());
9647         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9648         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false);
9649         expect_pending_htlcs_forwardable!(nodes[2]);
9650         expect_payment_received!(nodes[2], payment_hash_2, payment_secret_2, 200_000);
9651
9652         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
9653         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage_2);
9654 }
9655
9656 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
9657         let chanmon_cfgs = create_chanmon_cfgs(2);
9658         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9659         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9660         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9661
9662         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9663
9664         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
9665                 .with_features(InvoiceFeatures::known());
9666         let route = get_route!(nodes[0], payment_params, 10_000, TEST_FINAL_CLTV).unwrap();
9667
9668         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9669
9670         {
9671                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
9672                 check_added_monitors!(nodes[0], 1);
9673                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9674                 assert_eq!(events.len(), 1);
9675                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9676                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9677                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9678         }
9679         expect_pending_htlcs_forwardable!(nodes[1]);
9680         expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9681
9682         {
9683                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
9684                 check_added_monitors!(nodes[0], 1);
9685                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9686                 assert_eq!(events.len(), 1);
9687                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9688                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9689                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9690                 // At this point, nodes[1] would notice it has too much value for the payment. It will
9691                 // assume the second is a privacy attack (no longer particularly relevant
9692                 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9693                 // the first HTLC delivered above.
9694         }
9695
9696         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9697         nodes[1].node.process_pending_htlc_forwards();
9698
9699         if test_for_second_fail_panic {
9700                 // Now we go fail back the first HTLC from the user end.
9701                 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9702
9703                 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9704                 nodes[1].node.process_pending_htlc_forwards();
9705
9706                 check_added_monitors!(nodes[1], 1);
9707                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9708                 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9709
9710                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9711                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9712                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9713
9714                 let failure_events = nodes[0].node.get_and_clear_pending_events();
9715                 assert_eq!(failure_events.len(), 2);
9716                 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9717                 if let Event::PaymentPathFailed { .. } = failure_events[1] {} else { panic!(); }
9718         } else {
9719                 // Let the second HTLC fail and claim the first
9720                 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9721                 nodes[1].node.process_pending_htlc_forwards();
9722
9723                 check_added_monitors!(nodes[1], 1);
9724                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9725                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9726                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9727
9728                 expect_payment_failed_conditions!(nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9729
9730                 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9731         }
9732 }
9733
9734 #[test]
9735 fn test_dup_htlc_second_fail_panic() {
9736         // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9737         // value for the payment, we'd fail back both HTLCs after generating a `PaymentReceived` event.
9738         // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9739         // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9740         do_test_dup_htlc_second_rejected(true);
9741 }
9742
9743 #[test]
9744 fn test_dup_htlc_second_rejected() {
9745         // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9746         // simply reject the second HTLC but are still able to claim the first HTLC.
9747         do_test_dup_htlc_second_rejected(false);
9748 }
9749
9750 #[test]
9751 fn test_inconsistent_mpp_params() {
9752         // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9753         // such HTLC and allow the second to stay.
9754         let chanmon_cfgs = create_chanmon_cfgs(4);
9755         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9756         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9757         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9758
9759         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9760         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9761         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9762         create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9763
9764         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id())
9765                 .with_features(InvoiceFeatures::known());
9766         let mut route = get_route!(nodes[0], payment_params, 15_000_000, TEST_FINAL_CLTV).unwrap();
9767         assert_eq!(route.paths.len(), 2);
9768         route.paths.sort_by(|path_a, _| {
9769                 // Sort the path so that the path through nodes[1] comes first
9770                 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
9771                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9772         });
9773         let payment_params_opt = Some(payment_params);
9774
9775         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9776
9777         let cur_height = nodes[0].best_block_info().1;
9778         let payment_id = PaymentId([42; 32]);
9779         {
9780                 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();
9781                 check_added_monitors!(nodes[0], 1);
9782
9783                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9784                 assert_eq!(events.len(), 1);
9785                 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9786         }
9787         assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9788
9789         {
9790                 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();
9791                 check_added_monitors!(nodes[0], 1);
9792
9793                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9794                 assert_eq!(events.len(), 1);
9795                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9796
9797                 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9798                 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9799
9800                 expect_pending_htlcs_forwardable!(nodes[2]);
9801                 check_added_monitors!(nodes[2], 1);
9802
9803                 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9804                 assert_eq!(events.len(), 1);
9805                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9806
9807                 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9808                 check_added_monitors!(nodes[3], 0);
9809                 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9810
9811                 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9812                 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9813                 // post-payment_secrets) and fail back the new HTLC.
9814         }
9815         expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9816         nodes[3].node.process_pending_htlc_forwards();
9817         expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9818         nodes[3].node.process_pending_htlc_forwards();
9819
9820         check_added_monitors!(nodes[3], 1);
9821
9822         let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9823         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9824         commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9825
9826         expect_pending_htlcs_forwardable!(nodes[2]);
9827         check_added_monitors!(nodes[2], 1);
9828
9829         let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9830         nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9831         commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9832
9833         expect_payment_failed_conditions!(nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9834
9835         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();
9836         check_added_monitors!(nodes[0], 1);
9837
9838         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9839         assert_eq!(events.len(), 1);
9840         pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9841
9842         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9843 }
9844
9845 #[test]
9846 fn test_keysend_payments_to_public_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 _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9853         let network_graph = nodes[0].network_graph;
9854         let payer_pubkey = nodes[0].node.get_our_node_id();
9855         let payee_pubkey = nodes[1].node.get_our_node_id();
9856         let route_params = RouteParameters {
9857                 payment_params: PaymentParameters::for_keysend(payee_pubkey),
9858                 final_value_msat: 10000,
9859                 final_cltv_expiry_delta: 40,
9860         };
9861         let scorer = test_utils::TestScorer::with_penalty(0);
9862         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9863         let route = find_route(&payer_pubkey, &route_params, network_graph, None, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
9864
9865         let test_preimage = PaymentPreimage([42; 32]);
9866         let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9867         check_added_monitors!(nodes[0], 1);
9868         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9869         assert_eq!(events.len(), 1);
9870         let event = events.pop().unwrap();
9871         let path = vec![&nodes[1]];
9872         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9873         claim_payment(&nodes[0], &path, test_preimage);
9874 }
9875
9876 #[test]
9877 fn test_keysend_payments_to_private_node() {
9878         let chanmon_cfgs = create_chanmon_cfgs(2);
9879         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9880         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9881         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9882
9883         let payer_pubkey = nodes[0].node.get_our_node_id();
9884         let payee_pubkey = nodes[1].node.get_our_node_id();
9885         nodes[0].node.peer_connected(&payee_pubkey, &msgs::Init { features: InitFeatures::known(), remote_network_address: None });
9886         nodes[1].node.peer_connected(&payer_pubkey, &msgs::Init { features: InitFeatures::known(), remote_network_address: None });
9887
9888         let _chan = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
9889         let route_params = RouteParameters {
9890                 payment_params: PaymentParameters::for_keysend(payee_pubkey),
9891                 final_value_msat: 10000,
9892                 final_cltv_expiry_delta: 40,
9893         };
9894         let network_graph = nodes[0].network_graph;
9895         let first_hops = nodes[0].node.list_usable_channels();
9896         let scorer = test_utils::TestScorer::with_penalty(0);
9897         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9898         let route = find_route(
9899                 &payer_pubkey, &route_params, network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
9900                 nodes[0].logger, &scorer, &random_seed_bytes
9901         ).unwrap();
9902
9903         let test_preimage = PaymentPreimage([42; 32]);
9904         let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9905         check_added_monitors!(nodes[0], 1);
9906         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9907         assert_eq!(events.len(), 1);
9908         let event = events.pop().unwrap();
9909         let path = vec![&nodes[1]];
9910         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9911         claim_payment(&nodes[0], &path, test_preimage);
9912 }
9913
9914 #[test]
9915 fn test_double_partial_claim() {
9916         // Test what happens if a node receives a payment, generates a PaymentReceived event, the HTLCs
9917         // time out, the sender resends only some of the MPP parts, then the user processes the
9918         // PaymentReceived event, ensuring they don't inadvertently claim only part of the full payment
9919         // amount.
9920         let chanmon_cfgs = create_chanmon_cfgs(4);
9921         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9922         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9923         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9924
9925         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9926         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9927         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9928         create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9929
9930         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
9931         assert_eq!(route.paths.len(), 2);
9932         route.paths.sort_by(|path_a, _| {
9933                 // Sort the path so that the path through nodes[1] comes first
9934                 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
9935                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9936         });
9937
9938         send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 15_000_000, payment_hash, payment_secret);
9939         // nodes[3] has now received a PaymentReceived event...which it will take some (exorbitant)
9940         // amount of time to respond to.
9941
9942         // Connect some blocks to time out the payment
9943         connect_blocks(&nodes[3], TEST_FINAL_CLTV);
9944         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // To get the same height for sending later
9945
9946         expect_pending_htlcs_forwardable!(nodes[3]);
9947
9948         pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash);
9949
9950         // nodes[1] now retries one of the two paths...
9951         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
9952         check_added_monitors!(nodes[0], 2);
9953
9954         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9955         assert_eq!(events.len(), 2);
9956         pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
9957
9958         // At this point nodes[3] has received one half of the payment, and the user goes to handle
9959         // that PaymentReceived event they got hours ago and never handled...we should refuse to claim.
9960         nodes[3].node.claim_funds(payment_preimage);
9961         check_added_monitors!(nodes[3], 0);
9962         assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
9963 }
9964
9965 fn do_test_partial_claim_before_restart(persist_both_monitors: bool) {
9966         // Test what happens if a node receives an MPP payment, claims it, but crashes before
9967         // persisting the ChannelManager. If `persist_both_monitors` is false, also crash after only
9968         // updating one of the two channels' ChannelMonitors. As a result, on startup, we'll (a) still
9969         // have the PaymentReceived event, (b) have one (or two) channel(s) that goes on chain with the
9970         // HTLC preimage in them, and (c) optionally have one channel that is live off-chain but does
9971         // not have the preimage tied to the still-pending HTLC.
9972         //
9973         // To get to the correct state, on startup we should propagate the preimage to the
9974         // still-off-chain channel, claiming the HTLC as soon as the peer connects, with the monitor
9975         // receiving the preimage without a state update.
9976         //
9977         // Further, we should generate a `PaymentClaimed` event to inform the user that the payment was
9978         // definitely claimed.
9979         let chanmon_cfgs = create_chanmon_cfgs(4);
9980         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9981         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9982
9983         let persister: test_utils::TestPersister;
9984         let new_chain_monitor: test_utils::TestChainMonitor;
9985         let nodes_3_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
9986
9987         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9988
9989         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9990         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9991         let chan_id_persisted = create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known()).2;
9992         let chan_id_not_persisted = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known()).2;
9993
9994         // Create an MPP route for 15k sats, more than the default htlc-max of 10%
9995         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
9996         assert_eq!(route.paths.len(), 2);
9997         route.paths.sort_by(|path_a, _| {
9998                 // Sort the path so that the path through nodes[1] comes first
9999                 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
10000                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
10001         });
10002
10003         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
10004         check_added_monitors!(nodes[0], 2);
10005
10006         // Send the payment through to nodes[3] *without* clearing the PaymentReceived event
10007         let mut send_events = nodes[0].node.get_and_clear_pending_msg_events();
10008         assert_eq!(send_events.len(), 2);
10009         do_pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), send_events[0].clone(), true, false, None);
10010         do_pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), send_events[1].clone(), true, false, None);
10011
10012         // Now that we have an MPP payment pending, get the latest encoded copies of nodes[3]'s
10013         // monitors and ChannelManager, for use later, if we don't want to persist both monitors.
10014         let mut original_monitor = test_utils::TestVecWriter(Vec::new());
10015         if !persist_both_monitors {
10016                 for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
10017                         if outpoint.to_channel_id() == chan_id_not_persisted {
10018                                 assert!(original_monitor.0.is_empty());
10019                                 nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut original_monitor).unwrap();
10020                         }
10021                 }
10022         }
10023
10024         let mut original_manager = test_utils::TestVecWriter(Vec::new());
10025         nodes[3].node.write(&mut original_manager).unwrap();
10026
10027         expect_payment_received!(nodes[3], payment_hash, payment_secret, 15_000_000);
10028
10029         nodes[3].node.claim_funds(payment_preimage);
10030         check_added_monitors!(nodes[3], 2);
10031         expect_payment_claimed!(nodes[3], payment_hash, 15_000_000);
10032
10033         // Now fetch one of the two updated ChannelMonitors from nodes[3], and restart pretending we
10034         // crashed in between the two persistence calls - using one old ChannelMonitor and one new one,
10035         // with the old ChannelManager.
10036         let mut updated_monitor = test_utils::TestVecWriter(Vec::new());
10037         for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
10038                 if outpoint.to_channel_id() == chan_id_persisted {
10039                         assert!(updated_monitor.0.is_empty());
10040                         nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut updated_monitor).unwrap();
10041                 }
10042         }
10043         // If `persist_both_monitors` is set, get the second monitor here as well
10044         if persist_both_monitors {
10045                 for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
10046                         if outpoint.to_channel_id() == chan_id_not_persisted {
10047                                 assert!(original_monitor.0.is_empty());
10048                                 nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut original_monitor).unwrap();
10049                         }
10050                 }
10051         }
10052
10053         // Now restart nodes[3].
10054         persister = test_utils::TestPersister::new();
10055         let keys_manager = &chanmon_cfgs[3].keys_manager;
10056         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[3].chain_source), nodes[3].tx_broadcaster.clone(), nodes[3].logger, node_cfgs[3].fee_estimator, &persister, keys_manager);
10057         nodes[3].chain_monitor = &new_chain_monitor;
10058         let mut monitors = Vec::new();
10059         for mut monitor_data in [original_monitor, updated_monitor].iter() {
10060                 let (_, mut deserialized_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut &monitor_data.0[..], keys_manager).unwrap();
10061                 monitors.push(deserialized_monitor);
10062         }
10063
10064         let config = UserConfig::default();
10065         nodes_3_deserialized = {
10066                 let mut channel_monitors = HashMap::new();
10067                 for monitor in monitors.iter_mut() {
10068                         channel_monitors.insert(monitor.get_funding_txo().0, monitor);
10069                 }
10070                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut &original_manager.0[..], ChannelManagerReadArgs {
10071                         default_config: config,
10072                         keys_manager,
10073                         fee_estimator: node_cfgs[3].fee_estimator,
10074                         chain_monitor: nodes[3].chain_monitor,
10075                         tx_broadcaster: nodes[3].tx_broadcaster.clone(),
10076                         logger: nodes[3].logger,
10077                         channel_monitors,
10078                 }).unwrap().1
10079         };
10080         nodes[3].node = &nodes_3_deserialized;
10081
10082         for monitor in monitors {
10083                 // On startup the preimage should have been copied into the non-persisted monitor:
10084                 assert!(monitor.get_stored_preimages().contains_key(&payment_hash));
10085                 nodes[3].chain_monitor.watch_channel(monitor.get_funding_txo().0.clone(), monitor).unwrap();
10086         }
10087         check_added_monitors!(nodes[3], 2);
10088
10089         nodes[1].node.peer_disconnected(&nodes[3].node.get_our_node_id(), false);
10090         nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), false);
10091
10092         // During deserialization, we should have closed one channel and broadcast its latest
10093         // commitment transaction. We should also still have the original PaymentReceived event we
10094         // never finished processing.
10095         let events = nodes[3].node.get_and_clear_pending_events();
10096         assert_eq!(events.len(), if persist_both_monitors { 4 } else { 3 });
10097         if let Event::PaymentReceived { amount_msat: 15_000_000, .. } = events[0] { } else { panic!(); }
10098         if let Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } = events[1] { } else { panic!(); }
10099         if persist_both_monitors {
10100                 if let Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } = events[2] { } else { panic!(); }
10101         }
10102
10103         // On restart, we should also get a duplicate PaymentClaimed event as we persisted the
10104         // ChannelManager prior to handling the original one.
10105         if let Event::PaymentClaimed { payment_hash: our_payment_hash, amount_msat: 15_000_000, .. } =
10106                 events[if persist_both_monitors { 3 } else { 2 }]
10107         {
10108                 assert_eq!(payment_hash, our_payment_hash);
10109         } else { panic!(); }
10110
10111         assert_eq!(nodes[3].node.list_channels().len(), if persist_both_monitors { 0 } else { 1 });
10112         if !persist_both_monitors {
10113                 // If one of the two channels is still live, reveal the payment preimage over it.
10114
10115                 nodes[3].node.peer_connected(&nodes[2].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
10116                 let reestablish_1 = get_chan_reestablish_msgs!(nodes[3], nodes[2]);
10117                 nodes[2].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
10118                 let reestablish_2 = get_chan_reestablish_msgs!(nodes[2], nodes[3]);
10119
10120                 nodes[2].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish_1[0]);
10121                 get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, nodes[3].node.get_our_node_id());
10122                 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
10123
10124                 nodes[3].node.handle_channel_reestablish(&nodes[2].node.get_our_node_id(), &reestablish_2[0]);
10125
10126                 // Once we call `get_and_clear_pending_msg_events` the holding cell is cleared and the HTLC
10127                 // claim should fly.
10128                 let ds_msgs = nodes[3].node.get_and_clear_pending_msg_events();
10129                 check_added_monitors!(nodes[3], 1);
10130                 assert_eq!(ds_msgs.len(), 2);
10131                 if let MessageSendEvent::SendChannelUpdate { .. } = ds_msgs[1] {} else { panic!(); }
10132
10133                 let cs_updates = match ds_msgs[0] {
10134                         MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
10135                                 nodes[2].node.handle_update_fulfill_htlc(&nodes[3].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
10136                                 check_added_monitors!(nodes[2], 1);
10137                                 let cs_updates = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
10138                                 expect_payment_forwarded!(nodes[2], nodes[0], nodes[3], Some(1000), false, false);
10139                                 commitment_signed_dance!(nodes[2], nodes[3], updates.commitment_signed, false, true);
10140                                 cs_updates
10141                         }
10142                         _ => panic!(),
10143                 };
10144
10145                 nodes[0].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &cs_updates.update_fulfill_htlcs[0]);
10146                 commitment_signed_dance!(nodes[0], nodes[2], cs_updates.commitment_signed, false, true);
10147                 expect_payment_sent!(nodes[0], payment_preimage);
10148         }
10149 }
10150
10151 #[test]
10152 fn test_partial_claim_before_restart() {
10153         do_test_partial_claim_before_restart(false);
10154         do_test_partial_claim_before_restart(true);
10155 }
10156
10157 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
10158 #[derive(Clone, Copy, PartialEq)]
10159 enum ExposureEvent {
10160         /// Breach occurs at HTLC forwarding (see `send_htlc`)
10161         AtHTLCForward,
10162         /// Breach occurs at HTLC reception (see `update_add_htlc`)
10163         AtHTLCReception,
10164         /// Breach occurs at outbound update_fee (see `send_update_fee`)
10165         AtUpdateFeeOutbound,
10166 }
10167
10168 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool) {
10169         // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
10170         // policy.
10171         //
10172         // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
10173         // trimmed-to-dust HTLC outbound balance and this new payment as included on next
10174         // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
10175         // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
10176         // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
10177         // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
10178         // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
10179         // might be available again for HTLC processing once the dust bandwidth has cleared up.
10180
10181         let chanmon_cfgs = create_chanmon_cfgs(2);
10182         let mut config = test_default_channel_config();
10183         config.channel_options.max_dust_htlc_exposure_msat = 5_000_000; // default setting value
10184         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10185         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
10186         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10187
10188         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
10189         let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10190         open_channel.max_htlc_value_in_flight_msat = 50_000_000;
10191         open_channel.max_accepted_htlcs = 60;
10192         if on_holder_tx {
10193                 open_channel.dust_limit_satoshis = 546;
10194         }
10195         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
10196         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10197         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
10198
10199         let opt_anchors = false;
10200
10201         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
10202
10203         if on_holder_tx {
10204                 if let Some(mut chan) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&temporary_channel_id) {
10205                         chan.holder_dust_limit_satoshis = 546;
10206                 }
10207         }
10208
10209         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
10210         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()));
10211         check_added_monitors!(nodes[1], 1);
10212
10213         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()));
10214         check_added_monitors!(nodes[0], 1);
10215
10216         let (channel_ready, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
10217         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
10218         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
10219
10220         let dust_buffer_feerate = {
10221                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
10222                 let chan = chan_lock.by_id.get(&channel_id).unwrap();
10223                 chan.get_dust_buffer_feerate(None) as u64
10224         };
10225         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;
10226         let dust_outbound_htlc_on_holder_tx: u64 = config.channel_options.max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
10227
10228         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;
10229         let dust_inbound_htlc_on_holder_tx: u64 = config.channel_options.max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
10230
10231         let dust_htlc_on_counterparty_tx: u64 = 25;
10232         let dust_htlc_on_counterparty_tx_msat: u64 = config.channel_options.max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
10233
10234         if on_holder_tx {
10235                 if dust_outbound_balance {
10236                         // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
10237                         // Outbound dust balance: 4372 sats
10238                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
10239                         for i in 0..dust_outbound_htlc_on_holder_tx {
10240                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
10241                                 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at dust HTLC {}", i); }
10242                         }
10243                 } else {
10244                         // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
10245                         // Inbound dust balance: 4372 sats
10246                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
10247                         for _ in 0..dust_inbound_htlc_on_holder_tx {
10248                                 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
10249                         }
10250                 }
10251         } else {
10252                 if dust_outbound_balance {
10253                         // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
10254                         // Outbound dust balance: 5000 sats
10255                         for i in 0..dust_htlc_on_counterparty_tx {
10256                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
10257                                 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at dust HTLC {}", i); }
10258                         }
10259                 } else {
10260                         // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
10261                         // Inbound dust balance: 5000 sats
10262                         for _ in 0..dust_htlc_on_counterparty_tx {
10263                                 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
10264                         }
10265                 }
10266         }
10267
10268         let dust_overflow = dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx + 1);
10269         if exposure_breach_event == ExposureEvent::AtHTLCForward {
10270                 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 });
10271                 let mut config = UserConfig::default();
10272                 // With default dust exposure: 5000 sats
10273                 if on_holder_tx {
10274                         let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * (dust_outbound_htlc_on_holder_tx + 1);
10275                         let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * dust_inbound_htlc_on_holder_tx + dust_outbound_htlc_on_holder_tx_msat;
10276                         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)));
10277                 } else {
10278                         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)));
10279                 }
10280         } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
10281                 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 });
10282                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
10283                 check_added_monitors!(nodes[1], 1);
10284                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
10285                 assert_eq!(events.len(), 1);
10286                 let payment_event = SendEvent::from_event(events.remove(0));
10287                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
10288                 // With default dust exposure: 5000 sats
10289                 if on_holder_tx {
10290                         // Outbound dust balance: 6399 sats
10291                         let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
10292                         let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
10293                         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);
10294                 } else {
10295                         // Outbound dust balance: 5200 sats
10296                         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);
10297                 }
10298         } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
10299                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 2_500_000);
10300                 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at update_fee-swallowed HTLC", ); }
10301                 {
10302                         let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
10303                         *feerate_lock = *feerate_lock * 10;
10304                 }
10305                 nodes[0].node.timer_tick_occurred();
10306                 check_added_monitors!(nodes[0], 1);
10307                 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);
10308         }
10309
10310         let _ = nodes[0].node.get_and_clear_pending_msg_events();
10311         let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
10312         added_monitors.clear();
10313 }
10314
10315 #[test]
10316 fn test_max_dust_htlc_exposure() {
10317         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true);
10318         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true);
10319         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true);
10320         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false);
10321         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false);
10322         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false);
10323         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true);
10324         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false);
10325         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true);
10326         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false);
10327         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false);
10328         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true);
10329 }