Ensure all HTLCs for a claimed payment are claimed on startup
[rust-lightning] / lightning / src / ln / functional_tests.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
8 // licenses.
9
10 //! Tests that test standing up a network of ChannelManagers, creating channels, sending
11 //! payments/messages between them, and often checking the resulting ChannelMonitors are able to
12 //! claim outputs on-chain.
13
14 use chain;
15 use chain::{Confirm, Listen, Watch};
16 use chain::channelmonitor;
17 use chain::channelmonitor::{ChannelMonitor, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY};
18 use chain::transaction::OutPoint;
19 use chain::keysinterface::{BaseSign, KeysInterface};
20 use ln::{PaymentPreimage, PaymentSecret, PaymentHash};
21 use ln::channel::{commitment_tx_base_weight, COMMITMENT_TX_WEIGHT_PER_HTLC, CONCURRENT_INBOUND_HTLC_FEE_BUFFER, FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE, MIN_AFFORDABLE_HTLC_COUNT};
22 use ln::channelmanager::{ChannelManager, ChannelManagerReadArgs, PaymentId, RAACommitmentOrder, PaymentSendFailure, BREAKDOWN_TIMEOUT, MIN_CLTV_EXPIRY_DELTA, PAYMENT_EXPIRY_BLOCKS };
23 use ln::channel::{Channel, ChannelError};
24 use ln::{chan_utils, onion_utils};
25 use ln::chan_utils::{htlc_success_tx_weight, htlc_timeout_tx_weight, HTLCOutputInCommitment};
26 use routing::router::{PaymentParameters, Route, RouteHop, RouteParameters, find_route, get_route};
27 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
28 use ln::msgs;
29 use ln::msgs::{ChannelMessageHandler, RoutingMessageHandler, OptionalField, ErrorAction};
30 use util::enforcing_trait_impls::EnforcingSigner;
31 use util::{byte_utils, test_utils};
32 use util::events::{Event, MessageSendEvent, MessageSendEventsProvider, PaymentPurpose, ClosureReason};
33 use util::errors::APIError;
34 use util::ser::{Writeable, ReadableArgs};
35 use util::config::UserConfig;
36
37 use bitcoin::hash_types::BlockHash;
38 use bitcoin::blockdata::block::{Block, BlockHeader};
39 use bitcoin::blockdata::script::Builder;
40 use bitcoin::blockdata::opcodes;
41 use bitcoin::blockdata::constants::genesis_block;
42 use bitcoin::network::constants::Network;
43
44 use bitcoin::secp256k1::Secp256k1;
45 use bitcoin::secp256k1::{PublicKey,SecretKey};
46
47 use regex;
48
49 use io;
50 use prelude::*;
51 use alloc::collections::BTreeSet;
52 use core::default::Default;
53 use sync::{Arc, Mutex};
54
55 use ln::functional_test_utils::*;
56 use ln::chan_utils::CommitmentTransaction;
57
58 #[test]
59 fn test_insane_channel_opens() {
60         // Stand up a network of 2 nodes
61         use ln::channel::TOTAL_BITCOIN_SUPPLY_SATOSHIS;
62         let mut cfg = UserConfig::default();
63         cfg.peer_channel_config_limits.max_funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1;
64         let chanmon_cfgs = create_chanmon_cfgs(2);
65         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
66         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(cfg)]);
67         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
68
69         // Instantiate channel parameters where we push the maximum msats given our
70         // funding satoshis
71         let channel_value_sat = 31337; // same as funding satoshis
72         let channel_reserve_satoshis = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value_sat);
73         let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
74
75         // Have node0 initiate a channel to node1 with aforementioned parameters
76         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
77
78         // Extract the channel open message from node0 to node1
79         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
80
81         // Test helper that asserts we get the correct error string given a mutator
82         // that supposedly makes the channel open message insane
83         let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
84                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &message_mutator(open_channel_message.clone()));
85                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
86                 assert_eq!(msg_events.len(), 1);
87                 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
88                 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
89                         match action {
90                                 &ErrorAction::SendErrorMessage { .. } => {
91                                         nodes[1].logger.assert_log_regex("lightning::ln::channelmanager".to_string(), expected_regex, 1);
92                                 },
93                                 _ => panic!("unexpected event!"),
94                         }
95                 } else { assert!(false); }
96         };
97
98         use ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
99
100         // Test all mutations that would make the channel open message insane
101         insane_open_helper(format!("Per our config, funding must be at most {}. It was {}", TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1, TOTAL_BITCOIN_SUPPLY_SATOSHIS + 2).as_str(), |mut msg| { msg.funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 2; msg });
102         insane_open_helper(format!("Funding must be smaller than the total bitcoin supply. It was {}", TOTAL_BITCOIN_SUPPLY_SATOSHIS).as_str(), |mut msg| { msg.funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS; msg });
103
104         insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
105
106         insane_open_helper(r"push_msat \d+ was larger than channel amount minus reserve \(\d+\)", |mut msg| { msg.push_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000 + 1; msg });
107
108         insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
109
110         insane_open_helper(r"Minimum htlc value \(\d+\) was larger than full channel value \(\d+\)", |mut msg| { msg.htlc_minimum_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000; msg });
111
112         insane_open_helper("They wanted our payments to be delayed by a needlessly long period", |mut msg| { msg.to_self_delay = MAX_LOCAL_BREAKDOWN_TIMEOUT + 1; msg });
113
114         insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
115
116         insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
117 }
118
119 #[test]
120 fn test_funding_exceeds_no_wumbo_limit() {
121         // Test that if a peer does not support wumbo channels, we'll refuse to open a wumbo channel to
122         // them.
123         use ln::channel::MAX_FUNDING_SATOSHIS_NO_WUMBO;
124         let chanmon_cfgs = create_chanmon_cfgs(2);
125         let mut node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
126         node_cfgs[1].features = InitFeatures::known().clear_wumbo();
127         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
128         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
129
130         match nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), MAX_FUNDING_SATOSHIS_NO_WUMBO + 1, 0, 42, None) {
131                 Err(APIError::APIMisuseError { err }) => {
132                         assert_eq!(format!("funding_value must not exceed {}, it was {}", MAX_FUNDING_SATOSHIS_NO_WUMBO, MAX_FUNDING_SATOSHIS_NO_WUMBO + 1), err);
133                 },
134                 _ => panic!()
135         }
136 }
137
138 fn do_test_counterparty_no_reserve(send_from_initiator: bool) {
139         // A peer providing a channel_reserve_satoshis of 0 (or less than our dust limit) is insecure,
140         // but only for them. Because some LSPs do it with some level of trust of the clients (for a
141         // substantial UX improvement), we explicitly allow it. Because it's unlikely to happen often
142         // in normal testing, we test it explicitly here.
143         let chanmon_cfgs = create_chanmon_cfgs(2);
144         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
145         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
146         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
147
148         // Have node0 initiate a channel to node1 with aforementioned parameters
149         let mut push_amt = 100_000_000;
150         let feerate_per_kw = 253;
151         let opt_anchors = false;
152         push_amt -= feerate_per_kw as u64 * (commitment_tx_base_weight(opt_anchors) + 4 * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000 * 1000;
153         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
154
155         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, if send_from_initiator { 0 } else { push_amt }, 42, None).unwrap();
156         let mut open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
157         if !send_from_initiator {
158                 open_channel_message.channel_reserve_satoshis = 0;
159                 open_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
160         }
161         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel_message);
162
163         // Extract the channel accept message from node1 to node0
164         let mut accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
165         if send_from_initiator {
166                 accept_channel_message.channel_reserve_satoshis = 0;
167                 accept_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
168         }
169         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel_message);
170         {
171                 let mut lock;
172                 let mut chan = get_channel_ref!(if send_from_initiator { &nodes[1] } else { &nodes[0] }, lock, temp_channel_id);
173                 chan.holder_selected_channel_reserve_satoshis = 0;
174                 chan.holder_max_htlc_value_in_flight_msat = 100_000_000;
175         }
176
177         let funding_tx = sign_funding_transaction(&nodes[0], &nodes[1], 100_000, temp_channel_id);
178         let funding_msgs = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &funding_tx);
179         create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_msgs.0);
180
181         // nodes[0] should now be able to send the full balance to nodes[1], violating nodes[1]'s
182         // security model if it ever tries to send funds back to nodes[0] (but that's not our problem).
183         if send_from_initiator {
184                 send_payment(&nodes[0], &[&nodes[1]], 100_000_000
185                         // Note that for outbound channels we have to consider the commitment tx fee and the
186                         // "fee spike buffer", which is currently a multiple of the total commitment tx fee as
187                         // well as an additional HTLC.
188                         - FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE * commit_tx_fee_msat(feerate_per_kw, 2, opt_anchors));
189         } else {
190                 send_payment(&nodes[1], &[&nodes[0]], push_amt);
191         }
192 }
193
194 #[test]
195 fn test_counterparty_no_reserve() {
196         do_test_counterparty_no_reserve(true);
197         do_test_counterparty_no_reserve(false);
198 }
199
200 #[test]
201 fn test_async_inbound_update_fee() {
202         let chanmon_cfgs = create_chanmon_cfgs(2);
203         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
204         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
205         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
206         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
207
208         // balancing
209         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
210
211         // A                                        B
212         // update_fee                            ->
213         // send (1) commitment_signed            -.
214         //                                       <- update_add_htlc/commitment_signed
215         // send (2) RAA (awaiting remote revoke) -.
216         // (1) commitment_signed is delivered    ->
217         //                                       .- send (3) RAA (awaiting remote revoke)
218         // (2) RAA is delivered                  ->
219         //                                       .- send (4) commitment_signed
220         //                                       <- (3) RAA is delivered
221         // send (5) commitment_signed            -.
222         //                                       <- (4) commitment_signed is delivered
223         // send (6) RAA                          -.
224         // (5) commitment_signed is delivered    ->
225         //                                       <- RAA
226         // (6) RAA is delivered                  ->
227
228         // First nodes[0] generates an update_fee
229         {
230                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
231                 *feerate_lock += 20;
232         }
233         nodes[0].node.timer_tick_occurred();
234         check_added_monitors!(nodes[0], 1);
235
236         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
237         assert_eq!(events_0.len(), 1);
238         let (update_msg, commitment_signed) = match events_0[0] { // (1)
239                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
240                         (update_fee.as_ref(), commitment_signed)
241                 },
242                 _ => panic!("Unexpected event"),
243         };
244
245         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
246
247         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
248         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
249         nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
250         check_added_monitors!(nodes[1], 1);
251
252         let payment_event = {
253                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
254                 assert_eq!(events_1.len(), 1);
255                 SendEvent::from_event(events_1.remove(0))
256         };
257         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
258         assert_eq!(payment_event.msgs.len(), 1);
259
260         // ...now when the messages get delivered everyone should be happy
261         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
262         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
263         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
264         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
265         check_added_monitors!(nodes[0], 1);
266
267         // deliver(1), generate (3):
268         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
269         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
270         // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
271         check_added_monitors!(nodes[1], 1);
272
273         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
274         let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
275         assert!(bs_update.update_add_htlcs.is_empty()); // (4)
276         assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
277         assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
278         assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
279         assert!(bs_update.update_fee.is_none()); // (4)
280         check_added_monitors!(nodes[1], 1);
281
282         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
283         let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
284         assert!(as_update.update_add_htlcs.is_empty()); // (5)
285         assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
286         assert!(as_update.update_fail_htlcs.is_empty()); // (5)
287         assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
288         assert!(as_update.update_fee.is_none()); // (5)
289         check_added_monitors!(nodes[0], 1);
290
291         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
292         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
293         // only (6) so get_event_msg's assert(len == 1) passes
294         check_added_monitors!(nodes[0], 1);
295
296         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
297         let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
298         check_added_monitors!(nodes[1], 1);
299
300         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
301         check_added_monitors!(nodes[0], 1);
302
303         let events_2 = nodes[0].node.get_and_clear_pending_events();
304         assert_eq!(events_2.len(), 1);
305         match events_2[0] {
306                 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
307                 _ => panic!("Unexpected event"),
308         }
309
310         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
311         check_added_monitors!(nodes[1], 1);
312 }
313
314 #[test]
315 fn test_update_fee_unordered_raa() {
316         // Just the intro to the previous test followed by an out-of-order RAA (which caused a
317         // crash in an earlier version of the update_fee patch)
318         let chanmon_cfgs = create_chanmon_cfgs(2);
319         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
320         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
321         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
322         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
323
324         // balancing
325         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
326
327         // First nodes[0] generates an update_fee
328         {
329                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
330                 *feerate_lock += 20;
331         }
332         nodes[0].node.timer_tick_occurred();
333         check_added_monitors!(nodes[0], 1);
334
335         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
336         assert_eq!(events_0.len(), 1);
337         let update_msg = match events_0[0] { // (1)
338                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
339                         update_fee.as_ref()
340                 },
341                 _ => panic!("Unexpected event"),
342         };
343
344         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
345
346         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
347         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
348         nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
349         check_added_monitors!(nodes[1], 1);
350
351         let payment_event = {
352                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
353                 assert_eq!(events_1.len(), 1);
354                 SendEvent::from_event(events_1.remove(0))
355         };
356         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
357         assert_eq!(payment_event.msgs.len(), 1);
358
359         // ...now when the messages get delivered everyone should be happy
360         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
361         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
362         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
363         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
364         check_added_monitors!(nodes[0], 1);
365
366         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
367         check_added_monitors!(nodes[1], 1);
368
369         // We can't continue, sadly, because our (1) now has a bogus signature
370 }
371
372 #[test]
373 fn test_multi_flight_update_fee() {
374         let chanmon_cfgs = create_chanmon_cfgs(2);
375         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
376         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
377         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
378         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
379
380         // A                                        B
381         // update_fee/commitment_signed          ->
382         //                                       .- send (1) RAA and (2) commitment_signed
383         // update_fee (never committed)          ->
384         // (3) update_fee                        ->
385         // We have to manually generate the above update_fee, it is allowed by the protocol but we
386         // don't track which updates correspond to which revoke_and_ack responses so we're in
387         // AwaitingRAA mode and will not generate the update_fee yet.
388         //                                       <- (1) RAA delivered
389         // (3) is generated and send (4) CS      -.
390         // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
391         // know the per_commitment_point to use for it.
392         //                                       <- (2) commitment_signed delivered
393         // revoke_and_ack                        ->
394         //                                          B should send no response here
395         // (4) commitment_signed delivered       ->
396         //                                       <- RAA/commitment_signed delivered
397         // revoke_and_ack                        ->
398
399         // First nodes[0] generates an update_fee
400         let initial_feerate;
401         {
402                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
403                 initial_feerate = *feerate_lock;
404                 *feerate_lock = initial_feerate + 20;
405         }
406         nodes[0].node.timer_tick_occurred();
407         check_added_monitors!(nodes[0], 1);
408
409         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
410         assert_eq!(events_0.len(), 1);
411         let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
412                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
413                         (update_fee.as_ref().unwrap(), commitment_signed)
414                 },
415                 _ => panic!("Unexpected event"),
416         };
417
418         // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
419         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
420         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
421         let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
422         check_added_monitors!(nodes[1], 1);
423
424         // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
425         // transaction:
426         {
427                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
428                 *feerate_lock = initial_feerate + 40;
429         }
430         nodes[0].node.timer_tick_occurred();
431         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
432         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
433
434         // Create the (3) update_fee message that nodes[0] will generate before it does...
435         let mut update_msg_2 = msgs::UpdateFee {
436                 channel_id: update_msg_1.channel_id.clone(),
437                 feerate_per_kw: (initial_feerate + 30) as u32,
438         };
439
440         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
441
442         update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
443         // Deliver (3)
444         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
445
446         // Deliver (1), generating (3) and (4)
447         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
448         let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
449         check_added_monitors!(nodes[0], 1);
450         assert!(as_second_update.update_add_htlcs.is_empty());
451         assert!(as_second_update.update_fulfill_htlcs.is_empty());
452         assert!(as_second_update.update_fail_htlcs.is_empty());
453         assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
454         // Check that the update_fee newly generated matches what we delivered:
455         assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
456         assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
457
458         // Deliver (2) commitment_signed
459         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
460         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
461         check_added_monitors!(nodes[0], 1);
462         // No commitment_signed so get_event_msg's assert(len == 1) passes
463
464         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
465         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
466         check_added_monitors!(nodes[1], 1);
467
468         // Delever (4)
469         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
470         let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
471         check_added_monitors!(nodes[1], 1);
472
473         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
474         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
475         check_added_monitors!(nodes[0], 1);
476
477         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
478         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
479         // No commitment_signed so get_event_msg's assert(len == 1) passes
480         check_added_monitors!(nodes[0], 1);
481
482         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
483         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
484         check_added_monitors!(nodes[1], 1);
485 }
486
487 fn do_test_sanity_on_in_flight_opens(steps: u8) {
488         // Previously, we had issues deserializing channels when we hadn't connected the first block
489         // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
490         // serialization round-trips and simply do steps towards opening a channel and then drop the
491         // Node objects.
492
493         let chanmon_cfgs = create_chanmon_cfgs(2);
494         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
495         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
496         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
497
498         if steps & 0b1000_0000 != 0{
499                 let block = Block {
500                         header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
501                         txdata: vec![],
502                 };
503                 connect_block(&nodes[0], &block);
504                 connect_block(&nodes[1], &block);
505         }
506
507         if steps & 0x0f == 0 { return; }
508         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
509         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
510
511         if steps & 0x0f == 1 { return; }
512         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
513         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
514
515         if steps & 0x0f == 2 { return; }
516         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
517
518         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
519
520         if steps & 0x0f == 3 { return; }
521         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
522         check_added_monitors!(nodes[0], 0);
523         let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
524
525         if steps & 0x0f == 4 { return; }
526         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
527         {
528                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
529                 assert_eq!(added_monitors.len(), 1);
530                 assert_eq!(added_monitors[0].0, funding_output);
531                 added_monitors.clear();
532         }
533         let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
534
535         if steps & 0x0f == 5 { return; }
536         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
537         {
538                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
539                 assert_eq!(added_monitors.len(), 1);
540                 assert_eq!(added_monitors[0].0, funding_output);
541                 added_monitors.clear();
542         }
543
544         let events_4 = nodes[0].node.get_and_clear_pending_events();
545         assert_eq!(events_4.len(), 0);
546
547         if steps & 0x0f == 6 { return; }
548         create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
549
550         if steps & 0x0f == 7 { return; }
551         confirm_transaction_at(&nodes[0], &tx, 2);
552         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
553         create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
554 }
555
556 #[test]
557 fn test_sanity_on_in_flight_opens() {
558         do_test_sanity_on_in_flight_opens(0);
559         do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
560         do_test_sanity_on_in_flight_opens(1);
561         do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
562         do_test_sanity_on_in_flight_opens(2);
563         do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
564         do_test_sanity_on_in_flight_opens(3);
565         do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
566         do_test_sanity_on_in_flight_opens(4);
567         do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
568         do_test_sanity_on_in_flight_opens(5);
569         do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
570         do_test_sanity_on_in_flight_opens(6);
571         do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
572         do_test_sanity_on_in_flight_opens(7);
573         do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
574         do_test_sanity_on_in_flight_opens(8);
575         do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
576 }
577
578 #[test]
579 fn test_update_fee_vanilla() {
580         let chanmon_cfgs = create_chanmon_cfgs(2);
581         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
582         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
583         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
584         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
585
586         {
587                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
588                 *feerate_lock += 25;
589         }
590         nodes[0].node.timer_tick_occurred();
591         check_added_monitors!(nodes[0], 1);
592
593         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
594         assert_eq!(events_0.len(), 1);
595         let (update_msg, commitment_signed) = match events_0[0] {
596                         MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
597                         (update_fee.as_ref(), commitment_signed)
598                 },
599                 _ => panic!("Unexpected event"),
600         };
601         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
602
603         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
604         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
605         check_added_monitors!(nodes[1], 1);
606
607         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
608         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
609         check_added_monitors!(nodes[0], 1);
610
611         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
612         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
613         // No commitment_signed so get_event_msg's assert(len == 1) passes
614         check_added_monitors!(nodes[0], 1);
615
616         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
617         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
618         check_added_monitors!(nodes[1], 1);
619 }
620
621 #[test]
622 fn test_update_fee_that_funder_cannot_afford() {
623         let chanmon_cfgs = create_chanmon_cfgs(2);
624         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
625         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
626         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
627         let channel_value = 5000;
628         let push_sats = 700;
629         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, push_sats * 1000, InitFeatures::known(), InitFeatures::known());
630         let channel_id = chan.2;
631         let secp_ctx = Secp256k1::new();
632         let bs_channel_reserve_sats = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value);
633
634         let opt_anchors = false;
635
636         // Calculate the maximum feerate that A can afford. Note that we don't send an update_fee
637         // CONCURRENT_INBOUND_HTLC_FEE_BUFFER HTLCs before actually running out of local balance, so we
638         // calculate two different feerates here - the expected local limit as well as the expected
639         // remote limit.
640         let feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / (commitment_tx_base_weight(opt_anchors) + CONCURRENT_INBOUND_HTLC_FEE_BUFFER as u64 * COMMITMENT_TX_WEIGHT_PER_HTLC)) as u32;
641         let non_buffer_feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / commitment_tx_base_weight(opt_anchors)) as u32;
642         {
643                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
644                 *feerate_lock = feerate;
645         }
646         nodes[0].node.timer_tick_occurred();
647         check_added_monitors!(nodes[0], 1);
648         let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
649
650         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
651
652         commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
653
654         // Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate set above.
655         {
656                 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
657
658                 //We made sure neither party's funds are below the dust limit and there are no HTLCs here
659                 assert_eq!(commitment_tx.output.len(), 2);
660                 let total_fee: u64 = commit_tx_fee_msat(feerate, 0, opt_anchors) / 1000;
661                 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
662                 actual_fee = channel_value - actual_fee;
663                 assert_eq!(total_fee, actual_fee);
664         }
665
666         {
667                 // Increment the feerate by a small constant, accounting for rounding errors
668                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
669                 *feerate_lock += 4;
670         }
671         nodes[0].node.timer_tick_occurred();
672         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot afford to send new feerate at {}", feerate + 4), 1);
673         check_added_monitors!(nodes[0], 0);
674
675         const INITIAL_COMMITMENT_NUMBER: u64 = 281474976710654;
676
677         // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
678         // needed to sign the new commitment tx and (2) sign the new commitment tx.
679         let (local_revocation_basepoint, local_htlc_basepoint, local_funding) = {
680                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
681                 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
682                 let chan_signer = local_chan.get_signer();
683                 let pubkeys = chan_signer.pubkeys();
684                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
685                  pubkeys.funding_pubkey)
686         };
687         let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point, remote_funding) = {
688                 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
689                 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
690                 let chan_signer = remote_chan.get_signer();
691                 let pubkeys = chan_signer.pubkeys();
692                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
693                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
694                  pubkeys.funding_pubkey)
695         };
696
697         // Assemble the set of keys we can use for signatures for our commitment_signed message.
698         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
699                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
700
701         let res = {
702                 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
703                 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
704                 let local_chan_signer = local_chan.get_signer();
705                 let mut htlcs: Vec<(HTLCOutputInCommitment, ())> = vec![];
706                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
707                         INITIAL_COMMITMENT_NUMBER - 1,
708                         push_sats,
709                         channel_value - push_sats - commit_tx_fee_msat(non_buffer_feerate + 4, 0, opt_anchors) / 1000,
710                         opt_anchors, local_funding, remote_funding,
711                         commit_tx_keys.clone(),
712                         non_buffer_feerate + 4,
713                         &mut htlcs,
714                         &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
715                 );
716                 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
717         };
718
719         let commit_signed_msg = msgs::CommitmentSigned {
720                 channel_id: chan.2,
721                 signature: res.0,
722                 htlc_signatures: res.1
723         };
724
725         let update_fee = msgs::UpdateFee {
726                 channel_id: chan.2,
727                 feerate_per_kw: non_buffer_feerate + 4,
728         };
729
730         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_fee);
731
732         //While producing the commitment_signed response after handling a received update_fee request the
733         //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
734         //Should produce and error.
735         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
736         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
737         check_added_monitors!(nodes[1], 1);
738         check_closed_broadcast!(nodes[1], true);
739         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: String::from("Funding remote cannot afford proposed new fee") });
740 }
741
742 #[test]
743 fn test_update_fee_with_fundee_update_add_htlc() {
744         let chanmon_cfgs = create_chanmon_cfgs(2);
745         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
746         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
747         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
748         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
749
750         // balancing
751         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
752
753         {
754                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
755                 *feerate_lock += 20;
756         }
757         nodes[0].node.timer_tick_occurred();
758         check_added_monitors!(nodes[0], 1);
759
760         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
761         assert_eq!(events_0.len(), 1);
762         let (update_msg, commitment_signed) = match events_0[0] {
763                         MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
764                         (update_fee.as_ref(), commitment_signed)
765                 },
766                 _ => panic!("Unexpected event"),
767         };
768         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
769         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
770         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
771         check_added_monitors!(nodes[1], 1);
772
773         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 800000);
774
775         // nothing happens since node[1] is in AwaitingRemoteRevoke
776         nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
777         {
778                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
779                 assert_eq!(added_monitors.len(), 0);
780                 added_monitors.clear();
781         }
782         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
783         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
784         // node[1] has nothing to do
785
786         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
787         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
788         check_added_monitors!(nodes[0], 1);
789
790         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
791         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
792         // No commitment_signed so get_event_msg's assert(len == 1) passes
793         check_added_monitors!(nodes[0], 1);
794         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
795         check_added_monitors!(nodes[1], 1);
796         // AwaitingRemoteRevoke ends here
797
798         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
799         assert_eq!(commitment_update.update_add_htlcs.len(), 1);
800         assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
801         assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
802         assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
803         assert_eq!(commitment_update.update_fee.is_none(), true);
804
805         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
806         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
807         check_added_monitors!(nodes[0], 1);
808         let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
809
810         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
811         check_added_monitors!(nodes[1], 1);
812         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
813
814         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
815         check_added_monitors!(nodes[1], 1);
816         let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
817         // No commitment_signed so get_event_msg's assert(len == 1) passes
818
819         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
820         check_added_monitors!(nodes[0], 1);
821         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
822
823         expect_pending_htlcs_forwardable!(nodes[0]);
824
825         let events = nodes[0].node.get_and_clear_pending_events();
826         assert_eq!(events.len(), 1);
827         match events[0] {
828                 Event::PaymentReceived { .. } => { },
829                 _ => panic!("Unexpected event"),
830         };
831
832         claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
833
834         send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
835         send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
836         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
837         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
838         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
839 }
840
841 #[test]
842 fn test_update_fee() {
843         let chanmon_cfgs = create_chanmon_cfgs(2);
844         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
845         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
846         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
847         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
848         let channel_id = chan.2;
849
850         // A                                        B
851         // (1) update_fee/commitment_signed      ->
852         //                                       <- (2) revoke_and_ack
853         //                                       .- send (3) commitment_signed
854         // (4) update_fee/commitment_signed      ->
855         //                                       .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
856         //                                       <- (3) commitment_signed delivered
857         // send (6) revoke_and_ack               -.
858         //                                       <- (5) deliver revoke_and_ack
859         // (6) deliver revoke_and_ack            ->
860         //                                       .- send (7) commitment_signed in response to (4)
861         //                                       <- (7) deliver commitment_signed
862         // revoke_and_ack                        ->
863
864         // Create and deliver (1)...
865         let feerate;
866         {
867                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
868                 feerate = *feerate_lock;
869                 *feerate_lock = feerate + 20;
870         }
871         nodes[0].node.timer_tick_occurred();
872         check_added_monitors!(nodes[0], 1);
873
874         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
875         assert_eq!(events_0.len(), 1);
876         let (update_msg, commitment_signed) = match events_0[0] {
877                         MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
878                         (update_fee.as_ref(), commitment_signed)
879                 },
880                 _ => panic!("Unexpected event"),
881         };
882         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
883
884         // Generate (2) and (3):
885         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
886         let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
887         check_added_monitors!(nodes[1], 1);
888
889         // Deliver (2):
890         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
891         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
892         check_added_monitors!(nodes[0], 1);
893
894         // Create and deliver (4)...
895         {
896                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
897                 *feerate_lock = feerate + 30;
898         }
899         nodes[0].node.timer_tick_occurred();
900         check_added_monitors!(nodes[0], 1);
901         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
902         assert_eq!(events_0.len(), 1);
903         let (update_msg, commitment_signed) = match events_0[0] {
904                         MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
905                         (update_fee.as_ref(), commitment_signed)
906                 },
907                 _ => panic!("Unexpected event"),
908         };
909
910         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
911         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
912         check_added_monitors!(nodes[1], 1);
913         // ... creating (5)
914         let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
915         // No commitment_signed so get_event_msg's assert(len == 1) passes
916
917         // Handle (3), creating (6):
918         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
919         check_added_monitors!(nodes[0], 1);
920         let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
921         // No commitment_signed so get_event_msg's assert(len == 1) passes
922
923         // Deliver (5):
924         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
925         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
926         check_added_monitors!(nodes[0], 1);
927
928         // Deliver (6), creating (7):
929         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
930         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
931         assert!(commitment_update.update_add_htlcs.is_empty());
932         assert!(commitment_update.update_fulfill_htlcs.is_empty());
933         assert!(commitment_update.update_fail_htlcs.is_empty());
934         assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
935         assert!(commitment_update.update_fee.is_none());
936         check_added_monitors!(nodes[1], 1);
937
938         // Deliver (7)
939         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
940         check_added_monitors!(nodes[0], 1);
941         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
942         // No commitment_signed so get_event_msg's assert(len == 1) passes
943
944         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
945         check_added_monitors!(nodes[1], 1);
946         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
947
948         assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
949         assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
950         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
951         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
952         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
953 }
954
955 #[test]
956 fn fake_network_test() {
957         // Simple test which builds a network of ChannelManagers, connects them to each other, and
958         // tests that payments get routed and transactions broadcast in semi-reasonable ways.
959         let chanmon_cfgs = create_chanmon_cfgs(4);
960         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
961         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
962         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
963
964         // Create some initial channels
965         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
966         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
967         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
968
969         // Rebalance the network a bit by relaying one payment through all the channels...
970         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
971         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
972         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
973         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
974
975         // Send some more payments
976         send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
977         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
978         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
979
980         // Test failure packets
981         let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
982         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
983
984         // Add a new channel that skips 3
985         let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
986
987         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
988         send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
989         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
990         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
991         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
992         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
993         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
994
995         // Do some rebalance loop payments, simultaneously
996         let mut hops = Vec::with_capacity(3);
997         hops.push(RouteHop {
998                 pubkey: nodes[2].node.get_our_node_id(),
999                 node_features: NodeFeatures::empty(),
1000                 short_channel_id: chan_2.0.contents.short_channel_id,
1001                 channel_features: ChannelFeatures::empty(),
1002                 fee_msat: 0,
1003                 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1004         });
1005         hops.push(RouteHop {
1006                 pubkey: nodes[3].node.get_our_node_id(),
1007                 node_features: NodeFeatures::empty(),
1008                 short_channel_id: chan_3.0.contents.short_channel_id,
1009                 channel_features: ChannelFeatures::empty(),
1010                 fee_msat: 0,
1011                 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1012         });
1013         hops.push(RouteHop {
1014                 pubkey: nodes[1].node.get_our_node_id(),
1015                 node_features: NodeFeatures::known(),
1016                 short_channel_id: chan_4.0.contents.short_channel_id,
1017                 channel_features: ChannelFeatures::known(),
1018                 fee_msat: 1000000,
1019                 cltv_expiry_delta: TEST_FINAL_CLTV,
1020         });
1021         hops[1].fee_msat = chan_4.1.contents.fee_base_msat as u64 + chan_4.1.contents.fee_proportional_millionths as u64 * hops[2].fee_msat as u64 / 1000000;
1022         hops[0].fee_msat = chan_3.0.contents.fee_base_msat as u64 + chan_3.0.contents.fee_proportional_millionths as u64 * hops[1].fee_msat as u64 / 1000000;
1023         let payment_preimage_1 = send_along_route(&nodes[1], Route { paths: vec![hops], payment_params: None }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1024
1025         let mut hops = Vec::with_capacity(3);
1026         hops.push(RouteHop {
1027                 pubkey: nodes[3].node.get_our_node_id(),
1028                 node_features: NodeFeatures::empty(),
1029                 short_channel_id: chan_4.0.contents.short_channel_id,
1030                 channel_features: ChannelFeatures::empty(),
1031                 fee_msat: 0,
1032                 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1033         });
1034         hops.push(RouteHop {
1035                 pubkey: nodes[2].node.get_our_node_id(),
1036                 node_features: NodeFeatures::empty(),
1037                 short_channel_id: chan_3.0.contents.short_channel_id,
1038                 channel_features: ChannelFeatures::empty(),
1039                 fee_msat: 0,
1040                 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1041         });
1042         hops.push(RouteHop {
1043                 pubkey: nodes[1].node.get_our_node_id(),
1044                 node_features: NodeFeatures::known(),
1045                 short_channel_id: chan_2.0.contents.short_channel_id,
1046                 channel_features: ChannelFeatures::known(),
1047                 fee_msat: 1000000,
1048                 cltv_expiry_delta: TEST_FINAL_CLTV,
1049         });
1050         hops[1].fee_msat = chan_2.1.contents.fee_base_msat as u64 + chan_2.1.contents.fee_proportional_millionths as u64 * hops[2].fee_msat as u64 / 1000000;
1051         hops[0].fee_msat = chan_3.1.contents.fee_base_msat as u64 + chan_3.1.contents.fee_proportional_millionths as u64 * hops[1].fee_msat as u64 / 1000000;
1052         let payment_hash_2 = send_along_route(&nodes[1], Route { paths: vec![hops], payment_params: None }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1053
1054         // Claim the rebalances...
1055         fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1056         claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1057
1058         // Add a duplicate new channel from 2 to 4
1059         let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1060
1061         // Send some payments across both channels
1062         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1063         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1064         let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1065
1066
1067         route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
1068         let events = nodes[0].node.get_and_clear_pending_msg_events();
1069         assert_eq!(events.len(), 0);
1070         nodes[0].logger.assert_log_regex("lightning::ln::channelmanager".to_string(), regex::Regex::new(r"Cannot send value that would put us over the max HTLC value in flight our peer will accept \(\d+\)").unwrap(), 1);
1071
1072         //TODO: Test that routes work again here as we've been notified that the channel is full
1073
1074         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3);
1075         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4);
1076         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5);
1077
1078         // Close down the channels...
1079         close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1080         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
1081         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1082         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1083         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1084         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1085         close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1086         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1087         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1088         close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1089         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1090         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1091         close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
1092         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1093         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1094 }
1095
1096 #[test]
1097 fn holding_cell_htlc_counting() {
1098         // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1099         // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1100         // commitment dance rounds.
1101         let chanmon_cfgs = create_chanmon_cfgs(3);
1102         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1103         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1104         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1105         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1106         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1107
1108         let mut payments = Vec::new();
1109         for _ in 0..::ln::channel::OUR_MAX_HTLCS {
1110                 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1111                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
1112                 payments.push((payment_preimage, payment_hash));
1113         }
1114         check_added_monitors!(nodes[1], 1);
1115
1116         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1117         assert_eq!(events.len(), 1);
1118         let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1119         assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1120
1121         // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1122         // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1123         // another HTLC.
1124         let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1125         {
1126                 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)), true, APIError::ChannelUnavailable { ref err },
1127                         assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1128                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1129                 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1130         }
1131
1132         // This should also be true if we try to forward a payment.
1133         let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1134         {
1135                 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
1136                 check_added_monitors!(nodes[0], 1);
1137         }
1138
1139         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1140         assert_eq!(events.len(), 1);
1141         let payment_event = SendEvent::from_event(events.pop().unwrap());
1142         assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1143
1144         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1145         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1146         // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1147         // fails), the second will process the resulting failure and fail the HTLC backward.
1148         expect_pending_htlcs_forwardable!(nodes[1]);
1149         expect_pending_htlcs_forwardable!(nodes[1]);
1150         check_added_monitors!(nodes[1], 1);
1151
1152         let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1153         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1154         commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1155
1156         expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1157
1158         // Now forward all the pending HTLCs and claim them back
1159         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1160         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1161         check_added_monitors!(nodes[2], 1);
1162
1163         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1164         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1165         check_added_monitors!(nodes[1], 1);
1166         let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1167
1168         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1169         check_added_monitors!(nodes[1], 1);
1170         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1171
1172         for ref update in as_updates.update_add_htlcs.iter() {
1173                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1174         }
1175         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1176         check_added_monitors!(nodes[2], 1);
1177         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1178         check_added_monitors!(nodes[2], 1);
1179         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1180
1181         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1182         check_added_monitors!(nodes[1], 1);
1183         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1184         check_added_monitors!(nodes[1], 1);
1185         let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1186
1187         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1188         check_added_monitors!(nodes[2], 1);
1189
1190         expect_pending_htlcs_forwardable!(nodes[2]);
1191
1192         let events = nodes[2].node.get_and_clear_pending_events();
1193         assert_eq!(events.len(), payments.len());
1194         for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1195                 match event {
1196                         &Event::PaymentReceived { ref payment_hash, .. } => {
1197                                 assert_eq!(*payment_hash, *hash);
1198                         },
1199                         _ => panic!("Unexpected event"),
1200                 };
1201         }
1202
1203         for (preimage, _) in payments.drain(..) {
1204                 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1205         }
1206
1207         send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1208 }
1209
1210 #[test]
1211 fn duplicate_htlc_test() {
1212         // Test that we accept duplicate payment_hash HTLCs across the network and that
1213         // claiming/failing them are all separate and don't affect each other
1214         let chanmon_cfgs = create_chanmon_cfgs(6);
1215         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1216         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1217         let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1218
1219         // Create some initial channels to route via 3 to 4/5 from 0/1/2
1220         create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
1221         create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1222         create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1223         create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
1224         create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
1225
1226         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1227
1228         *nodes[0].network_payment_count.borrow_mut() -= 1;
1229         assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1230
1231         *nodes[0].network_payment_count.borrow_mut() -= 1;
1232         assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1233
1234         claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1235         fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1236         claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1237 }
1238
1239 #[test]
1240 fn test_duplicate_htlc_different_direction_onchain() {
1241         // Test that ChannelMonitor doesn't generate 2 preimage txn
1242         // when we have 2 HTLCs with same preimage that go across a node
1243         // in opposite directions, even with the same payment secret.
1244         let chanmon_cfgs = create_chanmon_cfgs(2);
1245         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1246         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1247         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1248
1249         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1250
1251         // balancing
1252         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1253
1254         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1255
1256         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1257         let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200).unwrap();
1258         send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1259
1260         // Provide preimage to node 0 by claiming payment
1261         nodes[0].node.claim_funds(payment_preimage);
1262         check_added_monitors!(nodes[0], 1);
1263
1264         // Broadcast node 1 commitment txn
1265         let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1266
1267         assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1268         let mut has_both_htlcs = 0; // check htlcs match ones committed
1269         for outp in remote_txn[0].output.iter() {
1270                 if outp.value == 800_000 / 1000 {
1271                         has_both_htlcs += 1;
1272                 } else if outp.value == 900_000 / 1000 {
1273                         has_both_htlcs += 1;
1274                 }
1275         }
1276         assert_eq!(has_both_htlcs, 2);
1277
1278         mine_transaction(&nodes[0], &remote_txn[0]);
1279         check_added_monitors!(nodes[0], 1);
1280         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
1281         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
1282
1283         // Check we only broadcast 1 timeout tx
1284         let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1285         assert_eq!(claim_txn.len(), 8);
1286         assert_eq!(claim_txn[1], claim_txn[4]);
1287         assert_eq!(claim_txn[2], claim_txn[5]);
1288         check_spends!(claim_txn[1], chan_1.3);
1289         check_spends!(claim_txn[2], claim_txn[1]);
1290         check_spends!(claim_txn[7], claim_txn[1]);
1291
1292         assert_eq!(claim_txn[0].input.len(), 1);
1293         assert_eq!(claim_txn[3].input.len(), 1);
1294         assert_eq!(claim_txn[0].input[0].previous_output, claim_txn[3].input[0].previous_output);
1295
1296         assert_eq!(claim_txn[0].input.len(), 1);
1297         assert_eq!(claim_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1298         check_spends!(claim_txn[0], remote_txn[0]);
1299         assert_eq!(remote_txn[0].output[claim_txn[0].input[0].previous_output.vout as usize].value, 800);
1300         assert_eq!(claim_txn[6].input.len(), 1);
1301         assert_eq!(claim_txn[6].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1302         check_spends!(claim_txn[6], remote_txn[0]);
1303         assert_eq!(remote_txn[0].output[claim_txn[6].input[0].previous_output.vout as usize].value, 900);
1304
1305         let events = nodes[0].node.get_and_clear_pending_msg_events();
1306         assert_eq!(events.len(), 3);
1307         for e in events {
1308                 match e {
1309                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1310                         MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1311                                 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1312                                 assert_eq!(msg.data, "Channel closed because commitment or closing transaction was confirmed on chain.");
1313                         },
1314                         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, .. } } => {
1315                                 assert!(update_add_htlcs.is_empty());
1316                                 assert!(update_fail_htlcs.is_empty());
1317                                 assert_eq!(update_fulfill_htlcs.len(), 1);
1318                                 assert!(update_fail_malformed_htlcs.is_empty());
1319                                 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1320                         },
1321                         _ => panic!("Unexpected event"),
1322                 }
1323         }
1324 }
1325
1326 #[test]
1327 fn test_basic_channel_reserve() {
1328         let chanmon_cfgs = create_chanmon_cfgs(2);
1329         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1330         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1331         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1332         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1333
1334         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1335         let channel_reserve = chan_stat.channel_reserve_msat;
1336
1337         // The 2* and +1 are for the fee spike reserve.
1338         let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], chan.2), 1 + 1, get_opt_anchors!(nodes[0], chan.2));
1339         let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1340         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send + 1);
1341         let err = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).err().unwrap();
1342         match err {
1343                 PaymentSendFailure::AllFailedRetrySafe(ref fails) => {
1344                         match &fails[0] {
1345                                 &APIError::ChannelUnavailable{ref err} =>
1346                                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1347                                 _ => panic!("Unexpected error variant"),
1348                         }
1349                 },
1350                 _ => panic!("Unexpected error variant"),
1351         }
1352         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1353         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);
1354
1355         send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1356 }
1357
1358 #[test]
1359 fn test_fee_spike_violation_fails_htlc() {
1360         let chanmon_cfgs = create_chanmon_cfgs(2);
1361         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1362         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1363         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1364         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1365
1366         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3460001);
1367         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1368         let secp_ctx = Secp256k1::new();
1369         let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1370
1371         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1372
1373         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1374         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &Some(payment_secret), cur_height, &None).unwrap();
1375         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1376         let msg = msgs::UpdateAddHTLC {
1377                 channel_id: chan.2,
1378                 htlc_id: 0,
1379                 amount_msat: htlc_msat,
1380                 payment_hash: payment_hash,
1381                 cltv_expiry: htlc_cltv,
1382                 onion_routing_packet: onion_packet,
1383         };
1384
1385         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1386
1387         // Now manually create the commitment_signed message corresponding to the update_add
1388         // nodes[0] just sent. In the code for construction of this message, "local" refers
1389         // to the sender of the message, and "remote" refers to the receiver.
1390
1391         let feerate_per_kw = get_feerate!(nodes[0], chan.2);
1392
1393         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1394
1395         // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1396         // needed to sign the new commitment tx and (2) sign the new commitment tx.
1397         let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1398                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
1399                 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
1400                 let chan_signer = local_chan.get_signer();
1401                 // Make the signer believe we validated another commitment, so we can release the secret
1402                 chan_signer.get_enforcement_state().last_holder_commitment -= 1;
1403
1404                 let pubkeys = chan_signer.pubkeys();
1405                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1406                  chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1407                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1408                  chan_signer.pubkeys().funding_pubkey)
1409         };
1410         let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1411                 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
1412                 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
1413                 let chan_signer = remote_chan.get_signer();
1414                 let pubkeys = chan_signer.pubkeys();
1415                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1416                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1417                  chan_signer.pubkeys().funding_pubkey)
1418         };
1419
1420         // Assemble the set of keys we can use for signatures for our commitment_signed message.
1421         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1422                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
1423
1424         // Build the remote commitment transaction so we can sign it, and then later use the
1425         // signature for the commitment_signed message.
1426         let local_chan_balance = 1313;
1427
1428         let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1429                 offered: false,
1430                 amount_msat: 3460001,
1431                 cltv_expiry: htlc_cltv,
1432                 payment_hash,
1433                 transaction_output_index: Some(1),
1434         };
1435
1436         let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1437
1438         let res = {
1439                 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
1440                 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
1441                 let local_chan_signer = local_chan.get_signer();
1442                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1443                         commitment_number,
1444                         95000,
1445                         local_chan_balance,
1446                         local_chan.opt_anchors(), local_funding, remote_funding,
1447                         commit_tx_keys.clone(),
1448                         feerate_per_kw,
1449                         &mut vec![(accepted_htlc_info, ())],
1450                         &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1451                 );
1452                 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
1453         };
1454
1455         let commit_signed_msg = msgs::CommitmentSigned {
1456                 channel_id: chan.2,
1457                 signature: res.0,
1458                 htlc_signatures: res.1
1459         };
1460
1461         // Send the commitment_signed message to the nodes[1].
1462         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1463         let _ = nodes[1].node.get_and_clear_pending_msg_events();
1464
1465         // Send the RAA to nodes[1].
1466         let raa_msg = msgs::RevokeAndACK {
1467                 channel_id: chan.2,
1468                 per_commitment_secret: local_secret,
1469                 next_per_commitment_point: next_local_point
1470         };
1471         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1472
1473         let events = nodes[1].node.get_and_clear_pending_msg_events();
1474         assert_eq!(events.len(), 1);
1475         // Make sure the HTLC failed in the way we expect.
1476         match events[0] {
1477                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1478                         assert_eq!(update_fail_htlcs.len(), 1);
1479                         update_fail_htlcs[0].clone()
1480                 },
1481                 _ => panic!("Unexpected event"),
1482         };
1483         nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1484                 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", ::hex::encode(raa_msg.channel_id)), 1);
1485
1486         check_added_monitors!(nodes[1], 2);
1487 }
1488
1489 #[test]
1490 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1491         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1492         // Set the fee rate for the channel very high, to the point where the fundee
1493         // sending any above-dust amount would result in a channel reserve violation.
1494         // In this test we check that we would be prevented from sending an HTLC in
1495         // this situation.
1496         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1497         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1498         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1499         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1500
1501         let opt_anchors = false;
1502
1503         let mut push_amt = 100_000_000;
1504         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1505         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1506
1507         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, InitFeatures::known(), InitFeatures::known());
1508
1509         // Sending exactly enough to hit the reserve amount should be accepted
1510         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1511                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1512         }
1513
1514         // However one more HTLC should be significantly over the reserve amount and fail.
1515         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1516         unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1517                 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1518         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1519         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);
1520 }
1521
1522 #[test]
1523 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1524         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1525         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1526         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1527         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1528         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1529
1530         let opt_anchors = false;
1531
1532         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1533         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1534         // transaction fee with 0 HTLCs (183 sats)).
1535         let mut push_amt = 100_000_000;
1536         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1537         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1538         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, InitFeatures::known(), InitFeatures::known());
1539
1540         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1541         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1542                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1543         }
1544
1545         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 700_000);
1546         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1547         let secp_ctx = Secp256k1::new();
1548         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1549         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1550         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1551         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 700_000, &Some(payment_secret), cur_height, &None).unwrap();
1552         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1553         let msg = msgs::UpdateAddHTLC {
1554                 channel_id: chan.2,
1555                 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1556                 amount_msat: htlc_msat,
1557                 payment_hash: payment_hash,
1558                 cltv_expiry: htlc_cltv,
1559                 onion_routing_packet: onion_packet,
1560         };
1561
1562         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1563         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1564         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);
1565         assert_eq!(nodes[0].node.list_channels().len(), 0);
1566         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1567         assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1568         check_added_monitors!(nodes[0], 1);
1569         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() });
1570 }
1571
1572 #[test]
1573 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1574         // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1575         // calculating our commitment transaction fee (this was previously broken).
1576         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1577         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1578
1579         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1580         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1581         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1582
1583         let opt_anchors = false;
1584
1585         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1586         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1587         // transaction fee with 0 HTLCs (183 sats)).
1588         let mut push_amt = 100_000_000;
1589         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1590         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1591         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt, InitFeatures::known(), InitFeatures::known());
1592
1593         let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1594                 + feerate_per_kw as u64 * htlc_success_tx_weight(opt_anchors) / 1000 * 1000 - 1;
1595         // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1596         // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1597         // commitment transaction fee.
1598         let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1599
1600         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1601         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1602                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1603         }
1604
1605         // One more than the dust amt should fail, however.
1606         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt + 1);
1607         unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1608                 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1609 }
1610
1611 #[test]
1612 fn test_chan_init_feerate_unaffordability() {
1613         // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to
1614         // channel reserve and feerate requirements.
1615         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1616         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1617         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1618         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1619         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1620
1621         let opt_anchors = false;
1622
1623         // Set the push_msat amount such that nodes[0] will not be able to afford to add even a single
1624         // HTLC.
1625         let mut push_amt = 100_000_000;
1626         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1627         assert_eq!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt + 1, 42, None).unwrap_err(),
1628                 APIError::APIMisuseError { err: "Funding amount (356) can't even pay fee for initial commitment transaction fee of 357.".to_string() });
1629
1630         // During open, we don't have a "counterparty channel reserve" to check against, so that
1631         // requirement only comes into play on the open_channel handling side.
1632         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1633         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt, 42, None).unwrap();
1634         let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
1635         open_channel_msg.push_msat += 1;
1636         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel_msg);
1637
1638         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1639         assert_eq!(msg_events.len(), 1);
1640         match msg_events[0] {
1641                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1642                         assert_eq!(msg.data, "Insufficient funding amount for initial reserve");
1643                 },
1644                 _ => panic!("Unexpected event"),
1645         }
1646 }
1647
1648 #[test]
1649 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1650         // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1651         // calculating our counterparty's commitment transaction fee (this was previously broken).
1652         let chanmon_cfgs = create_chanmon_cfgs(2);
1653         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1654         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1655         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1656         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000, InitFeatures::known(), InitFeatures::known());
1657
1658         let payment_amt = 46000; // Dust amount
1659         // In the previous code, these first four payments would succeed.
1660         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1661         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1662         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1663         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1664
1665         // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1666         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1667         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1668         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1669         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1670         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1671
1672         // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1673         // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1674         // transaction fee and therefore perceived this next payment as a channel reserve violation.
1675         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1676 }
1677
1678 #[test]
1679 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1680         let chanmon_cfgs = create_chanmon_cfgs(3);
1681         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1682         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1683         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1684         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1685         let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1686
1687         let feemsat = 239;
1688         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1689         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1690         let feerate = get_feerate!(nodes[0], chan.2);
1691         let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
1692
1693         // Add a 2* and +1 for the fee spike reserve.
1694         let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1695         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;
1696         let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1697
1698         // Add a pending HTLC.
1699         let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1700         let payment_event_1 = {
1701                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1702                 check_added_monitors!(nodes[0], 1);
1703
1704                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1705                 assert_eq!(events.len(), 1);
1706                 SendEvent::from_event(events.remove(0))
1707         };
1708         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1709
1710         // Attempt to trigger a channel reserve violation --> payment failure.
1711         let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2, opt_anchors);
1712         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;
1713         let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1714         let (route_2, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_2);
1715
1716         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1717         let secp_ctx = Secp256k1::new();
1718         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1719         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1720         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1721         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height, &None).unwrap();
1722         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1723         let msg = msgs::UpdateAddHTLC {
1724                 channel_id: chan.2,
1725                 htlc_id: 1,
1726                 amount_msat: htlc_msat + 1,
1727                 payment_hash: our_payment_hash_1,
1728                 cltv_expiry: htlc_cltv,
1729                 onion_routing_packet: onion_packet,
1730         };
1731
1732         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1733         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1734         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1735         assert_eq!(nodes[1].node.list_channels().len(), 1);
1736         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1737         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1738         check_added_monitors!(nodes[1], 1);
1739         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() });
1740 }
1741
1742 #[test]
1743 fn test_inbound_outbound_capacity_is_not_zero() {
1744         let chanmon_cfgs = create_chanmon_cfgs(2);
1745         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1746         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1747         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1748         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1749         let channels0 = node_chanmgrs[0].list_channels();
1750         let channels1 = node_chanmgrs[1].list_channels();
1751         assert_eq!(channels0.len(), 1);
1752         assert_eq!(channels1.len(), 1);
1753
1754         let reserve = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100000);
1755         assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1756         assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1757
1758         assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1759         assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1760 }
1761
1762 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64, opt_anchors: bool) -> u64 {
1763         (commitment_tx_base_weight(opt_anchors) + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1764 }
1765
1766 #[test]
1767 fn test_channel_reserve_holding_cell_htlcs() {
1768         let chanmon_cfgs = create_chanmon_cfgs(3);
1769         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1770         // When this test was written, the default base fee floated based on the HTLC count.
1771         // It is now fixed, so we simply set the fee to the expected value here.
1772         let mut config = test_default_channel_config();
1773         config.channel_options.forwarding_fee_base_msat = 239;
1774         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1775         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1776         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1777         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1778
1779         let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1780         let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1781
1782         let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1783         let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1784
1785         macro_rules! expect_forward {
1786                 ($node: expr) => {{
1787                         let mut events = $node.node.get_and_clear_pending_msg_events();
1788                         assert_eq!(events.len(), 1);
1789                         check_added_monitors!($node, 1);
1790                         let payment_event = SendEvent::from_event(events.remove(0));
1791                         payment_event
1792                 }}
1793         }
1794
1795         let feemsat = 239; // set above
1796         let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1797         let feerate = get_feerate!(nodes[0], chan_1.2);
1798         let opt_anchors = get_opt_anchors!(nodes[0], chan_1.2);
1799
1800         let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1801
1802         // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1803         {
1804                 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_0);
1805                 route.paths[0].last_mut().unwrap().fee_msat += 1;
1806                 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1807                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1808                         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)));
1809                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1810                 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);
1811         }
1812
1813         // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1814         // nodes[0]'s wealth
1815         loop {
1816                 let amt_msat = recv_value_0 + total_fee_msat;
1817                 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1818                 // Also, ensure that each payment has enough to be over the dust limit to
1819                 // ensure it'll be included in each commit tx fee calculation.
1820                 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1821                 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1822                 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1823                         break;
1824                 }
1825                 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0);
1826
1827                 let (stat01_, stat11_, stat12_, stat22_) = (
1828                         get_channel_value_stat!(nodes[0], chan_1.2),
1829                         get_channel_value_stat!(nodes[1], chan_1.2),
1830                         get_channel_value_stat!(nodes[1], chan_2.2),
1831                         get_channel_value_stat!(nodes[2], chan_2.2),
1832                 );
1833
1834                 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1835                 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1836                 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1837                 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1838                 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1839         }
1840
1841         // adding pending output.
1842         // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1843         // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1844         // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1845         // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1846         // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1847         // cases where 1 msat over X amount will cause a payment failure, but anything less than
1848         // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1849         // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1850         // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1851         // policy.
1852         let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1853         let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1854         let amt_msat_1 = recv_value_1 + total_fee_msat;
1855
1856         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);
1857         let payment_event_1 = {
1858                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1859                 check_added_monitors!(nodes[0], 1);
1860
1861                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1862                 assert_eq!(events.len(), 1);
1863                 SendEvent::from_event(events.remove(0))
1864         };
1865         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1866
1867         // channel reserve test with htlc pending output > 0
1868         let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1869         {
1870                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_2 + 1);
1871                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1872                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1873                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1874         }
1875
1876         // split the rest to test holding cell
1877         let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1878         let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1879         let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1880         let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1881         {
1882                 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
1883                 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);
1884         }
1885
1886         // now see if they go through on both sides
1887         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);
1888         // but this will stuck in the holding cell
1889         nodes[0].node.send_payment(&route_21, our_payment_hash_21, &Some(our_payment_secret_21)).unwrap();
1890         check_added_monitors!(nodes[0], 0);
1891         let events = nodes[0].node.get_and_clear_pending_events();
1892         assert_eq!(events.len(), 0);
1893
1894         // test with outbound holding cell amount > 0
1895         {
1896                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22+1);
1897                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1898                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1899                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1900                 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);
1901         }
1902
1903         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);
1904         // this will also stuck in the holding cell
1905         nodes[0].node.send_payment(&route_22, our_payment_hash_22, &Some(our_payment_secret_22)).unwrap();
1906         check_added_monitors!(nodes[0], 0);
1907         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1908         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1909
1910         // flush the pending htlc
1911         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1912         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1913         check_added_monitors!(nodes[1], 1);
1914
1915         // the pending htlc should be promoted to committed
1916         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1917         check_added_monitors!(nodes[0], 1);
1918         let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1919
1920         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1921         let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1922         // No commitment_signed so get_event_msg's assert(len == 1) passes
1923         check_added_monitors!(nodes[0], 1);
1924
1925         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1926         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1927         check_added_monitors!(nodes[1], 1);
1928
1929         expect_pending_htlcs_forwardable!(nodes[1]);
1930
1931         let ref payment_event_11 = expect_forward!(nodes[1]);
1932         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1933         commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1934
1935         expect_pending_htlcs_forwardable!(nodes[2]);
1936         expect_payment_received!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
1937
1938         // flush the htlcs in the holding cell
1939         assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1940         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1941         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1942         commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1943         expect_pending_htlcs_forwardable!(nodes[1]);
1944
1945         let ref payment_event_3 = expect_forward!(nodes[1]);
1946         assert_eq!(payment_event_3.msgs.len(), 2);
1947         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1948         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1949
1950         commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1951         expect_pending_htlcs_forwardable!(nodes[2]);
1952
1953         let events = nodes[2].node.get_and_clear_pending_events();
1954         assert_eq!(events.len(), 2);
1955         match events[0] {
1956                 Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
1957                         assert_eq!(our_payment_hash_21, *payment_hash);
1958                         assert_eq!(recv_value_21, amt);
1959                         match &purpose {
1960                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1961                                         assert!(payment_preimage.is_none());
1962                                         assert_eq!(our_payment_secret_21, *payment_secret);
1963                                 },
1964                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
1965                         }
1966                 },
1967                 _ => panic!("Unexpected event"),
1968         }
1969         match events[1] {
1970                 Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
1971                         assert_eq!(our_payment_hash_22, *payment_hash);
1972                         assert_eq!(recv_value_22, amt);
1973                         match &purpose {
1974                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1975                                         assert!(payment_preimage.is_none());
1976                                         assert_eq!(our_payment_secret_22, *payment_secret);
1977                                 },
1978                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
1979                         }
1980                 },
1981                 _ => panic!("Unexpected event"),
1982         }
1983
1984         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
1985         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
1986         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
1987
1988         let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1, opt_anchors);
1989         let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
1990         send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
1991
1992         let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
1993         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);
1994         let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
1995         assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
1996         assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
1997
1998         let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
1999         assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2000 }
2001
2002 #[test]
2003 fn channel_reserve_in_flight_removes() {
2004         // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2005         // can send to its counterparty, but due to update ordering, the other side may not yet have
2006         // considered those HTLCs fully removed.
2007         // This tests that we don't count HTLCs which will not be included in the next remote
2008         // commitment transaction towards the reserve value (as it implies no commitment transaction
2009         // will be generated which violates the remote reserve value).
2010         // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2011         // To test this we:
2012         //  * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2013         //    you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2014         //    you only consider the value of the first HTLC, it may not),
2015         //  * start routing a third HTLC from A to B,
2016         //  * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2017         //    the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2018         //  * deliver the first fulfill from B
2019         //  * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2020         //    claim,
2021         //  * deliver A's response CS and RAA.
2022         //    This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2023         //    removed it fully. B now has the push_msat plus the first two HTLCs in value.
2024         //  * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2025         //    of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2026         let chanmon_cfgs = create_chanmon_cfgs(2);
2027         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2028         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2029         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2030         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2031
2032         let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
2033         // Route the first two HTLCs.
2034         let (payment_preimage_1, _, _) = route_payment(&nodes[0], &[&nodes[1]], b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000);
2035         let (payment_preimage_2, _, _) = route_payment(&nodes[0], &[&nodes[1]], 20000);
2036
2037         // Start routing the third HTLC (this is just used to get everyone in the right state).
2038         let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
2039         let send_1 = {
2040                 nodes[0].node.send_payment(&route, payment_hash_3, &Some(payment_secret_3)).unwrap();
2041                 check_added_monitors!(nodes[0], 1);
2042                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2043                 assert_eq!(events.len(), 1);
2044                 SendEvent::from_event(events.remove(0))
2045         };
2046
2047         // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2048         // initial fulfill/CS.
2049         assert!(nodes[1].node.claim_funds(payment_preimage_1));
2050         check_added_monitors!(nodes[1], 1);
2051         let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2052
2053         // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2054         // remove the second HTLC when we send the HTLC back from B to A.
2055         assert!(nodes[1].node.claim_funds(payment_preimage_2));
2056         check_added_monitors!(nodes[1], 1);
2057         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2058
2059         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2060         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2061         check_added_monitors!(nodes[0], 1);
2062         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2063         expect_payment_sent_without_paths!(nodes[0], payment_preimage_1);
2064
2065         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2066         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2067         check_added_monitors!(nodes[1], 1);
2068         // B is already AwaitingRAA, so cant generate a CS here
2069         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2070
2071         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2072         check_added_monitors!(nodes[1], 1);
2073         let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2074
2075         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2076         check_added_monitors!(nodes[0], 1);
2077         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2078
2079         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2080         check_added_monitors!(nodes[1], 1);
2081         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2082
2083         // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2084         // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2085         // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2086         // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2087         // on-chain as necessary).
2088         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2089         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2090         check_added_monitors!(nodes[0], 1);
2091         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2092         expect_payment_sent_without_paths!(nodes[0], payment_preimage_2);
2093
2094         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2095         check_added_monitors!(nodes[1], 1);
2096         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2097
2098         expect_pending_htlcs_forwardable!(nodes[1]);
2099         expect_payment_received!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2100
2101         // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2102         // resolve the second HTLC from A's point of view.
2103         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2104         check_added_monitors!(nodes[0], 1);
2105         expect_payment_path_successful!(nodes[0]);
2106         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2107
2108         // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2109         // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2110         let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2111         let send_2 = {
2112                 nodes[1].node.send_payment(&route, payment_hash_4, &Some(payment_secret_4)).unwrap();
2113                 check_added_monitors!(nodes[1], 1);
2114                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2115                 assert_eq!(events.len(), 1);
2116                 SendEvent::from_event(events.remove(0))
2117         };
2118
2119         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2120         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2121         check_added_monitors!(nodes[0], 1);
2122         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2123
2124         // Now just resolve all the outstanding messages/HTLCs for completeness...
2125
2126         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2127         check_added_monitors!(nodes[1], 1);
2128         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2129
2130         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2131         check_added_monitors!(nodes[1], 1);
2132
2133         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2134         check_added_monitors!(nodes[0], 1);
2135         expect_payment_path_successful!(nodes[0]);
2136         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2137
2138         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2139         check_added_monitors!(nodes[1], 1);
2140         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2141
2142         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2143         check_added_monitors!(nodes[0], 1);
2144
2145         expect_pending_htlcs_forwardable!(nodes[0]);
2146         expect_payment_received!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2147
2148         claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2149         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2150 }
2151
2152 #[test]
2153 fn channel_monitor_network_test() {
2154         // Simple test which builds a network of ChannelManagers, connects them to each other, and
2155         // tests that ChannelMonitor is able to recover from various states.
2156         let chanmon_cfgs = create_chanmon_cfgs(5);
2157         let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2158         let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2159         let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2160
2161         // Create some initial channels
2162         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2163         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2164         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
2165         let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
2166
2167         // Make sure all nodes are at the same starting height
2168         connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2169         connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2170         connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2171         connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2172         connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2173
2174         // Rebalance the network a bit by relaying one payment through all the channels...
2175         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2176         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2177         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2178         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2179
2180         // Simple case with no pending HTLCs:
2181         nodes[1].node.force_close_channel(&chan_1.2, &nodes[0].node.get_our_node_id()).unwrap();
2182         check_added_monitors!(nodes[1], 1);
2183         check_closed_broadcast!(nodes[1], true);
2184         {
2185                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2186                 assert_eq!(node_txn.len(), 1);
2187                 mine_transaction(&nodes[0], &node_txn[0]);
2188                 check_added_monitors!(nodes[0], 1);
2189                 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
2190         }
2191         check_closed_broadcast!(nodes[0], true);
2192         assert_eq!(nodes[0].node.list_channels().len(), 0);
2193         assert_eq!(nodes[1].node.list_channels().len(), 1);
2194         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2195         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2196
2197         // One pending HTLC is discarded by the force-close:
2198         let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
2199
2200         // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2201         // broadcasted until we reach the timelock time).
2202         nodes[1].node.force_close_channel(&chan_2.2, &nodes[2].node.get_our_node_id()).unwrap();
2203         check_closed_broadcast!(nodes[1], true);
2204         check_added_monitors!(nodes[1], 1);
2205         {
2206                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2207                 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2208                 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2209                 mine_transaction(&nodes[2], &node_txn[0]);
2210                 check_added_monitors!(nodes[2], 1);
2211                 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
2212         }
2213         check_closed_broadcast!(nodes[2], true);
2214         assert_eq!(nodes[1].node.list_channels().len(), 0);
2215         assert_eq!(nodes[2].node.list_channels().len(), 1);
2216         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2217         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2218
2219         macro_rules! claim_funds {
2220                 ($node: expr, $prev_node: expr, $preimage: expr) => {
2221                         {
2222                                 assert!($node.node.claim_funds($preimage));
2223                                 check_added_monitors!($node, 1);
2224
2225                                 let events = $node.node.get_and_clear_pending_msg_events();
2226                                 assert_eq!(events.len(), 1);
2227                                 match events[0] {
2228                                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2229                                                 assert!(update_add_htlcs.is_empty());
2230                                                 assert!(update_fail_htlcs.is_empty());
2231                                                 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2232                                         },
2233                                         _ => panic!("Unexpected event"),
2234                                 };
2235                         }
2236                 }
2237         }
2238
2239         // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2240         // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2241         nodes[2].node.force_close_channel(&chan_3.2, &nodes[3].node.get_our_node_id()).unwrap();
2242         check_added_monitors!(nodes[2], 1);
2243         check_closed_broadcast!(nodes[2], true);
2244         let node2_commitment_txid;
2245         {
2246                 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2247                 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2248                 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2249                 node2_commitment_txid = node_txn[0].txid();
2250
2251                 // Claim the payment on nodes[3], giving it knowledge of the preimage
2252                 claim_funds!(nodes[3], nodes[2], payment_preimage_1);
2253                 mine_transaction(&nodes[3], &node_txn[0]);
2254                 check_added_monitors!(nodes[3], 1);
2255                 check_preimage_claim(&nodes[3], &node_txn);
2256         }
2257         check_closed_broadcast!(nodes[3], true);
2258         assert_eq!(nodes[2].node.list_channels().len(), 0);
2259         assert_eq!(nodes[3].node.list_channels().len(), 1);
2260         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
2261         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2262
2263         // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2264         // confusing us in the following tests.
2265         let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2266
2267         // One pending HTLC to time out:
2268         let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
2269         // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2270         // buffer space).
2271
2272         let (close_chan_update_1, close_chan_update_2) = {
2273                 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2274                 let events = nodes[3].node.get_and_clear_pending_msg_events();
2275                 assert_eq!(events.len(), 2);
2276                 let close_chan_update_1 = match events[0] {
2277                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2278                                 msg.clone()
2279                         },
2280                         _ => panic!("Unexpected event"),
2281                 };
2282                 match events[1] {
2283                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2284                                 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2285                         },
2286                         _ => panic!("Unexpected event"),
2287                 }
2288                 check_added_monitors!(nodes[3], 1);
2289
2290                 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2291                 {
2292                         let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2293                         node_txn.retain(|tx| {
2294                                 if tx.input[0].previous_output.txid == node2_commitment_txid {
2295                                         false
2296                                 } else { true }
2297                         });
2298                 }
2299
2300                 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2301
2302                 // Claim the payment on nodes[4], giving it knowledge of the preimage
2303                 claim_funds!(nodes[4], nodes[3], payment_preimage_2);
2304
2305                 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2306                 let events = nodes[4].node.get_and_clear_pending_msg_events();
2307                 assert_eq!(events.len(), 2);
2308                 let close_chan_update_2 = match events[0] {
2309                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2310                                 msg.clone()
2311                         },
2312                         _ => panic!("Unexpected event"),
2313                 };
2314                 match events[1] {
2315                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2316                                 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2317                         },
2318                         _ => panic!("Unexpected event"),
2319                 }
2320                 check_added_monitors!(nodes[4], 1);
2321                 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2322
2323                 mine_transaction(&nodes[4], &node_txn[0]);
2324                 check_preimage_claim(&nodes[4], &node_txn);
2325                 (close_chan_update_1, close_chan_update_2)
2326         };
2327         nodes[3].net_graph_msg_handler.handle_channel_update(&close_chan_update_2).unwrap();
2328         nodes[4].net_graph_msg_handler.handle_channel_update(&close_chan_update_1).unwrap();
2329         assert_eq!(nodes[3].node.list_channels().len(), 0);
2330         assert_eq!(nodes[4].node.list_channels().len(), 0);
2331
2332         nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon).unwrap();
2333         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2334         check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed);
2335 }
2336
2337 #[test]
2338 fn test_justice_tx() {
2339         // Test justice txn built on revoked HTLC-Success tx, against both sides
2340         let mut alice_config = UserConfig::default();
2341         alice_config.channel_options.announced_channel = true;
2342         alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
2343         alice_config.own_channel_config.our_to_self_delay = 6 * 24 * 5;
2344         let mut bob_config = UserConfig::default();
2345         bob_config.channel_options.announced_channel = true;
2346         bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
2347         bob_config.own_channel_config.our_to_self_delay = 6 * 24 * 3;
2348         let user_cfgs = [Some(alice_config), Some(bob_config)];
2349         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2350         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2351         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2352         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2353         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2354         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2355         // Create some new channels:
2356         let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2357
2358         // A pending HTLC which will be revoked:
2359         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2360         // Get the will-be-revoked local txn from nodes[0]
2361         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2362         assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2363         assert_eq!(revoked_local_txn[0].input.len(), 1);
2364         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2365         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2366         assert_eq!(revoked_local_txn[1].input.len(), 1);
2367         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2368         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2369         // Revoke the old state
2370         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2371
2372         {
2373                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2374                 {
2375                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2376                         assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2377                         assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2378
2379                         check_spends!(node_txn[0], revoked_local_txn[0]);
2380                         node_txn.swap_remove(0);
2381                         node_txn.truncate(1);
2382                 }
2383                 check_added_monitors!(nodes[1], 1);
2384                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2385                 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2386
2387                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2388                 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2389                 // Verify broadcast of revoked HTLC-timeout
2390                 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2391                 check_added_monitors!(nodes[0], 1);
2392                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2393                 // Broadcast revoked HTLC-timeout on node 1
2394                 mine_transaction(&nodes[1], &node_txn[1]);
2395                 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2396         }
2397         get_announce_close_broadcast_events(&nodes, 0, 1);
2398
2399         assert_eq!(nodes[0].node.list_channels().len(), 0);
2400         assert_eq!(nodes[1].node.list_channels().len(), 0);
2401
2402         // We test justice_tx build by A on B's revoked HTLC-Success tx
2403         // Create some new channels:
2404         let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2405         {
2406                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2407                 node_txn.clear();
2408         }
2409
2410         // A pending HTLC which will be revoked:
2411         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2412         // Get the will-be-revoked local txn from B
2413         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2414         assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2415         assert_eq!(revoked_local_txn[0].input.len(), 1);
2416         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2417         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2418         // Revoke the old state
2419         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2420         {
2421                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2422                 {
2423                         let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2424                         assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2425                         assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2426
2427                         check_spends!(node_txn[0], revoked_local_txn[0]);
2428                         node_txn.swap_remove(0);
2429                 }
2430                 check_added_monitors!(nodes[0], 1);
2431                 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2432
2433                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2434                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2435                 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2436                 check_added_monitors!(nodes[1], 1);
2437                 mine_transaction(&nodes[0], &node_txn[1]);
2438                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2439                 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2440         }
2441         get_announce_close_broadcast_events(&nodes, 0, 1);
2442         assert_eq!(nodes[0].node.list_channels().len(), 0);
2443         assert_eq!(nodes[1].node.list_channels().len(), 0);
2444 }
2445
2446 #[test]
2447 fn revoked_output_claim() {
2448         // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2449         // transaction is broadcast by its counterparty
2450         let chanmon_cfgs = create_chanmon_cfgs(2);
2451         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2452         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2453         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2454         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2455         // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2456         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2457         assert_eq!(revoked_local_txn.len(), 1);
2458         // Only output is the full channel value back to nodes[0]:
2459         assert_eq!(revoked_local_txn[0].output.len(), 1);
2460         // Send a payment through, updating everyone's latest commitment txn
2461         send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2462
2463         // Inform nodes[1] that nodes[0] broadcast a stale tx
2464         mine_transaction(&nodes[1], &revoked_local_txn[0]);
2465         check_added_monitors!(nodes[1], 1);
2466         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2467         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2468         assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2469
2470         check_spends!(node_txn[0], revoked_local_txn[0]);
2471         check_spends!(node_txn[1], chan_1.3);
2472
2473         // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2474         mine_transaction(&nodes[0], &revoked_local_txn[0]);
2475         get_announce_close_broadcast_events(&nodes, 0, 1);
2476         check_added_monitors!(nodes[0], 1);
2477         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2478 }
2479
2480 #[test]
2481 fn claim_htlc_outputs_shared_tx() {
2482         // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2483         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2484         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2485         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2486         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2487         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2488
2489         // Create some new channel:
2490         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2491
2492         // Rebalance the network to generate htlc in the two directions
2493         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
2494         // 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
2495         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2496         let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2497
2498         // Get the will-be-revoked local txn from node[0]
2499         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2500         assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2501         assert_eq!(revoked_local_txn[0].input.len(), 1);
2502         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2503         assert_eq!(revoked_local_txn[1].input.len(), 1);
2504         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2505         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2506         check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2507
2508         //Revoke the old state
2509         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2510
2511         {
2512                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2513                 check_added_monitors!(nodes[0], 1);
2514                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2515                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2516                 check_added_monitors!(nodes[1], 1);
2517                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2518                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2519                 expect_payment_failed!(nodes[1], payment_hash_2, true);
2520
2521                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2522                 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment
2523
2524                 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2525                 check_spends!(node_txn[0], revoked_local_txn[0]);
2526
2527                 let mut witness_lens = BTreeSet::new();
2528                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2529                 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2530                 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2531                 assert_eq!(witness_lens.len(), 3);
2532                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2533                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2534                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2535
2536                 // Next nodes[1] broadcasts its current local tx state:
2537                 assert_eq!(node_txn[1].input.len(), 1);
2538                 assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
2539         }
2540         get_announce_close_broadcast_events(&nodes, 0, 1);
2541         assert_eq!(nodes[0].node.list_channels().len(), 0);
2542         assert_eq!(nodes[1].node.list_channels().len(), 0);
2543 }
2544
2545 #[test]
2546 fn claim_htlc_outputs_single_tx() {
2547         // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2548         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2549         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2550         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2551         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2552         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2553
2554         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2555
2556         // Rebalance the network to generate htlc in the two directions
2557         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
2558         // 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
2559         // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2560         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2561         let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2562
2563         // Get the will-be-revoked local txn from node[0]
2564         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2565
2566         //Revoke the old state
2567         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2568
2569         {
2570                 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2571                 check_added_monitors!(nodes[0], 1);
2572                 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2573                 check_added_monitors!(nodes[1], 1);
2574                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2575                 let mut events = nodes[0].node.get_and_clear_pending_events();
2576                 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2577                 match events[1] {
2578                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2579                         _ => panic!("Unexpected event"),
2580                 }
2581
2582                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2583                 expect_payment_failed!(nodes[1], payment_hash_2, true);
2584
2585                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2586                 assert_eq!(node_txn.len(), 9);
2587                 // ChannelMonitor: justice tx revoked offered htlc, justice tx revoked received htlc, justice tx revoked to_local (3)
2588                 // ChannelManager: local commmitment + local HTLC-timeout (2)
2589                 // ChannelMonitor: bumped justice tx, after one increase, bumps on HTLC aren't generated not being substantial anymore, bump on revoked to_local isn't generated due to more room for expiration (2)
2590                 // ChannelMonitor: local commitment + local HTLC-timeout (2)
2591
2592                 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2593                 assert_eq!(node_txn[0].input.len(), 1);
2594                 check_spends!(node_txn[0], chan_1.3);
2595                 assert_eq!(node_txn[1].input.len(), 1);
2596                 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2597                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2598                 check_spends!(node_txn[1], node_txn[0]);
2599
2600                 // Justice transactions are indices 1-2-4
2601                 assert_eq!(node_txn[2].input.len(), 1);
2602                 assert_eq!(node_txn[3].input.len(), 1);
2603                 assert_eq!(node_txn[4].input.len(), 1);
2604
2605                 check_spends!(node_txn[2], revoked_local_txn[0]);
2606                 check_spends!(node_txn[3], revoked_local_txn[0]);
2607                 check_spends!(node_txn[4], revoked_local_txn[0]);
2608
2609                 let mut witness_lens = BTreeSet::new();
2610                 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2611                 witness_lens.insert(node_txn[3].input[0].witness.last().unwrap().len());
2612                 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2613                 assert_eq!(witness_lens.len(), 3);
2614                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2615                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2616                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2617         }
2618         get_announce_close_broadcast_events(&nodes, 0, 1);
2619         assert_eq!(nodes[0].node.list_channels().len(), 0);
2620         assert_eq!(nodes[1].node.list_channels().len(), 0);
2621 }
2622
2623 #[test]
2624 fn test_htlc_on_chain_success() {
2625         // Test that in case of a unilateral close onchain, we detect the state of output and pass
2626         // the preimage backward accordingly. So here we test that ChannelManager is
2627         // broadcasting the right event to other nodes in payment path.
2628         // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2629         // A --------------------> B ----------------------> C (preimage)
2630         // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2631         // commitment transaction was broadcast.
2632         // Then, B should learn the preimage from said transactions, attempting to claim backwards
2633         // towards B.
2634         // B should be able to claim via preimage if A then broadcasts its local tx.
2635         // Finally, when A sees B's latest local commitment transaction it should be able to claim
2636         // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2637         // PaymentSent event).
2638
2639         let chanmon_cfgs = create_chanmon_cfgs(3);
2640         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2641         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2642         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2643
2644         // Create some initial channels
2645         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2646         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2647
2648         // Ensure all nodes are at the same height
2649         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2650         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2651         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2652         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2653
2654         // Rebalance the network a bit by relaying one payment through all the channels...
2655         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2656         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2657
2658         let (our_payment_preimage, payment_hash_1, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2659         let (our_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2660
2661         // Broadcast legit commitment tx from C on B's chain
2662         // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2663         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2664         assert_eq!(commitment_tx.len(), 1);
2665         check_spends!(commitment_tx[0], chan_2.3);
2666         nodes[2].node.claim_funds(our_payment_preimage);
2667         nodes[2].node.claim_funds(our_payment_preimage_2);
2668         check_added_monitors!(nodes[2], 2);
2669         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2670         assert!(updates.update_add_htlcs.is_empty());
2671         assert!(updates.update_fail_htlcs.is_empty());
2672         assert!(updates.update_fail_malformed_htlcs.is_empty());
2673         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2674
2675         mine_transaction(&nodes[2], &commitment_tx[0]);
2676         check_closed_broadcast!(nodes[2], true);
2677         check_added_monitors!(nodes[2], 1);
2678         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2679         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)
2680         assert_eq!(node_txn.len(), 5);
2681         assert_eq!(node_txn[0], node_txn[3]);
2682         assert_eq!(node_txn[1], node_txn[4]);
2683         assert_eq!(node_txn[2], commitment_tx[0]);
2684         check_spends!(node_txn[0], commitment_tx[0]);
2685         check_spends!(node_txn[1], commitment_tx[0]);
2686         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2687         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2688         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2689         assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2690         assert_eq!(node_txn[0].lock_time, 0);
2691         assert_eq!(node_txn[1].lock_time, 0);
2692
2693         // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2694         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2695         connect_block(&nodes[1], &Block { header, txdata: node_txn});
2696         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2697         {
2698                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2699                 assert_eq!(added_monitors.len(), 1);
2700                 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2701                 added_monitors.clear();
2702         }
2703         let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2704         assert_eq!(forwarded_events.len(), 3);
2705         match forwarded_events[0] {
2706                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2707                 _ => panic!("Unexpected event"),
2708         }
2709         let chan_id = Some(chan_1.2);
2710         match forwarded_events[1] {
2711                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
2712                         assert_eq!(fee_earned_msat, Some(1000));
2713                         assert_eq!(prev_channel_id, chan_id);
2714                         assert_eq!(claim_from_onchain_tx, true);
2715                         assert_eq!(next_channel_id, Some(chan_2.2));
2716                 },
2717                 _ => panic!()
2718         }
2719         match forwarded_events[2] {
2720                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
2721                         assert_eq!(fee_earned_msat, Some(1000));
2722                         assert_eq!(prev_channel_id, chan_id);
2723                         assert_eq!(claim_from_onchain_tx, true);
2724                         assert_eq!(next_channel_id, Some(chan_2.2));
2725                 },
2726                 _ => panic!()
2727         }
2728         let events = nodes[1].node.get_and_clear_pending_msg_events();
2729         {
2730                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2731                 assert_eq!(added_monitors.len(), 2);
2732                 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2733                 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2734                 added_monitors.clear();
2735         }
2736         assert_eq!(events.len(), 3);
2737         match events[0] {
2738                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2739                 _ => panic!("Unexpected event"),
2740         }
2741         match events[1] {
2742                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2743                 _ => panic!("Unexpected event"),
2744         }
2745
2746         match events[2] {
2747                 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, .. } } => {
2748                         assert!(update_add_htlcs.is_empty());
2749                         assert!(update_fail_htlcs.is_empty());
2750                         assert_eq!(update_fulfill_htlcs.len(), 1);
2751                         assert!(update_fail_malformed_htlcs.is_empty());
2752                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2753                 },
2754                 _ => panic!("Unexpected event"),
2755         };
2756         macro_rules! check_tx_local_broadcast {
2757                 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2758                         let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2759                         assert_eq!(node_txn.len(), 3);
2760                         // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2761                         // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2762                         check_spends!(node_txn[1], $commitment_tx);
2763                         check_spends!(node_txn[2], $commitment_tx);
2764                         assert_ne!(node_txn[1].lock_time, 0);
2765                         assert_ne!(node_txn[2].lock_time, 0);
2766                         if $htlc_offered {
2767                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2768                                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2769                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2770                                 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2771                         } else {
2772                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2773                                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2774                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2775                                 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2776                         }
2777                         check_spends!(node_txn[0], $chan_tx);
2778                         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2779                         node_txn.clear();
2780                 } }
2781         }
2782         // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2783         // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2784         // timeout-claim of the output that nodes[2] just claimed via success.
2785         check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2786
2787         // Broadcast legit commitment tx from A on B's chain
2788         // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
2789         let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2790         check_spends!(node_a_commitment_tx[0], chan_1.3);
2791         mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2792         check_closed_broadcast!(nodes[1], true);
2793         check_added_monitors!(nodes[1], 1);
2794         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2795         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2796         assert_eq!(node_txn.len(), 6); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 3 (HTLC-Success, 2* RBF bumps of above HTLC txn)
2797         let commitment_spend =
2798                 if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2799                         check_spends!(node_txn[1], commitment_tx[0]);
2800                         check_spends!(node_txn[2], commitment_tx[0]);
2801                         assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2802                         &node_txn[0]
2803                 } else {
2804                         check_spends!(node_txn[0], commitment_tx[0]);
2805                         check_spends!(node_txn[1], commitment_tx[0]);
2806                         assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2807                         &node_txn[2]
2808                 };
2809
2810         check_spends!(commitment_spend, node_a_commitment_tx[0]);
2811         assert_eq!(commitment_spend.input.len(), 2);
2812         assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2813         assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2814         assert_eq!(commitment_spend.lock_time, 0);
2815         assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2816         check_spends!(node_txn[3], chan_1.3);
2817         assert_eq!(node_txn[3].input[0].witness.clone().last().unwrap().len(), 71);
2818         check_spends!(node_txn[4], node_txn[3]);
2819         check_spends!(node_txn[5], node_txn[3]);
2820         // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2821         // we already checked the same situation with A.
2822
2823         // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2824         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2825         connect_block(&nodes[0], &Block { header, txdata: vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()] });
2826         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2827         check_closed_broadcast!(nodes[0], true);
2828         check_added_monitors!(nodes[0], 1);
2829         let events = nodes[0].node.get_and_clear_pending_events();
2830         assert_eq!(events.len(), 5);
2831         let mut first_claimed = false;
2832         for event in events {
2833                 match event {
2834                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
2835                                 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
2836                                         assert!(!first_claimed);
2837                                         first_claimed = true;
2838                                 } else {
2839                                         assert_eq!(payment_preimage, our_payment_preimage_2);
2840                                         assert_eq!(payment_hash, payment_hash_2);
2841                                 }
2842                         },
2843                         Event::PaymentPathSuccessful { .. } => {},
2844                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
2845                         _ => panic!("Unexpected event"),
2846                 }
2847         }
2848         check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0], chan_1.3);
2849 }
2850
2851 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2852         // Test that in case of a unilateral close onchain, we detect the state of output and
2853         // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2854         // broadcasting the right event to other nodes in payment path.
2855         // A ------------------> B ----------------------> C (timeout)
2856         //    B's commitment tx                 C's commitment tx
2857         //            \                                  \
2858         //         B's HTLC timeout tx               B's timeout tx
2859
2860         let chanmon_cfgs = create_chanmon_cfgs(3);
2861         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2862         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2863         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2864         *nodes[0].connect_style.borrow_mut() = connect_style;
2865         *nodes[1].connect_style.borrow_mut() = connect_style;
2866         *nodes[2].connect_style.borrow_mut() = connect_style;
2867
2868         // Create some intial channels
2869         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2870         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2871
2872         // Rebalance the network a bit by relaying one payment thorugh all the channels...
2873         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2874         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2875
2876         let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2877
2878         // Broadcast legit commitment tx from C on B's chain
2879         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2880         check_spends!(commitment_tx[0], chan_2.3);
2881         nodes[2].node.fail_htlc_backwards(&payment_hash);
2882         check_added_monitors!(nodes[2], 0);
2883         expect_pending_htlcs_forwardable!(nodes[2]);
2884         check_added_monitors!(nodes[2], 1);
2885
2886         let events = nodes[2].node.get_and_clear_pending_msg_events();
2887         assert_eq!(events.len(), 1);
2888         match events[0] {
2889                 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, .. } } => {
2890                         assert!(update_add_htlcs.is_empty());
2891                         assert!(!update_fail_htlcs.is_empty());
2892                         assert!(update_fulfill_htlcs.is_empty());
2893                         assert!(update_fail_malformed_htlcs.is_empty());
2894                         assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2895                 },
2896                 _ => panic!("Unexpected event"),
2897         };
2898         mine_transaction(&nodes[2], &commitment_tx[0]);
2899         check_closed_broadcast!(nodes[2], true);
2900         check_added_monitors!(nodes[2], 1);
2901         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2902         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2903         assert_eq!(node_txn.len(), 1);
2904         check_spends!(node_txn[0], chan_2.3);
2905         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2906
2907         // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2908         // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2909         connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2910         mine_transaction(&nodes[1], &commitment_tx[0]);
2911         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2912         let timeout_tx;
2913         {
2914                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2915                 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
2916                 assert_eq!(node_txn[0], node_txn[3]);
2917                 assert_eq!(node_txn[1], node_txn[4]);
2918
2919                 check_spends!(node_txn[2], commitment_tx[0]);
2920                 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2921
2922                 check_spends!(node_txn[0], chan_2.3);
2923                 check_spends!(node_txn[1], node_txn[0]);
2924                 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2925                 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2926
2927                 timeout_tx = node_txn[2].clone();
2928                 node_txn.clear();
2929         }
2930
2931         mine_transaction(&nodes[1], &timeout_tx);
2932         check_added_monitors!(nodes[1], 1);
2933         check_closed_broadcast!(nodes[1], true);
2934         {
2935                 // B will rebroadcast a fee-bumped timeout transaction here.
2936                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2937                 assert_eq!(node_txn.len(), 1);
2938                 check_spends!(node_txn[0], commitment_tx[0]);
2939         }
2940
2941         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2942         {
2943                 // B may rebroadcast its own holder commitment transaction here, as a safeguard against
2944                 // some incredibly unlikely partial-eclipse-attack scenarios. That said, because the
2945                 // original commitment_tx[0] (also spending chan_2.3) has reached ANTI_REORG_DELAY B really
2946                 // shouldn't broadcast anything here, and in some connect style scenarios we do not.
2947                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2948                 if node_txn.len() == 1 {
2949                         check_spends!(node_txn[0], chan_2.3);
2950                 } else {
2951                         assert_eq!(node_txn.len(), 0);
2952                 }
2953         }
2954
2955         expect_pending_htlcs_forwardable!(nodes[1]);
2956         check_added_monitors!(nodes[1], 1);
2957         let events = nodes[1].node.get_and_clear_pending_msg_events();
2958         assert_eq!(events.len(), 1);
2959         match events[0] {
2960                 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, .. } } => {
2961                         assert!(update_add_htlcs.is_empty());
2962                         assert!(!update_fail_htlcs.is_empty());
2963                         assert!(update_fulfill_htlcs.is_empty());
2964                         assert!(update_fail_malformed_htlcs.is_empty());
2965                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2966                 },
2967                 _ => panic!("Unexpected event"),
2968         };
2969
2970         // Broadcast legit commitment tx from B on A's chain
2971         let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
2972         check_spends!(commitment_tx[0], chan_1.3);
2973
2974         mine_transaction(&nodes[0], &commitment_tx[0]);
2975         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2976
2977         check_closed_broadcast!(nodes[0], true);
2978         check_added_monitors!(nodes[0], 1);
2979         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2980         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 commitment tx, ChannelMonitor : 1 timeout tx
2981         assert_eq!(node_txn.len(), 2);
2982         check_spends!(node_txn[0], chan_1.3);
2983         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2984         check_spends!(node_txn[1], commitment_tx[0]);
2985         assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2986 }
2987
2988 #[test]
2989 fn test_htlc_on_chain_timeout() {
2990         do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
2991         do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
2992         do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
2993 }
2994
2995 #[test]
2996 fn test_simple_commitment_revoked_fail_backward() {
2997         // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
2998         // and fail backward accordingly.
2999
3000         let chanmon_cfgs = create_chanmon_cfgs(3);
3001         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3002         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3003         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3004
3005         // Create some initial channels
3006         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3007         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3008
3009         let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3010         // Get the will-be-revoked local txn from nodes[2]
3011         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3012         // Revoke the old state
3013         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3014
3015         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3016
3017         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3018         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3019         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3020         check_added_monitors!(nodes[1], 1);
3021         check_closed_broadcast!(nodes[1], true);
3022
3023         expect_pending_htlcs_forwardable!(nodes[1]);
3024         check_added_monitors!(nodes[1], 1);
3025         let events = nodes[1].node.get_and_clear_pending_msg_events();
3026         assert_eq!(events.len(), 1);
3027         match events[0] {
3028                 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, .. } } => {
3029                         assert!(update_add_htlcs.is_empty());
3030                         assert_eq!(update_fail_htlcs.len(), 1);
3031                         assert!(update_fulfill_htlcs.is_empty());
3032                         assert!(update_fail_malformed_htlcs.is_empty());
3033                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3034
3035                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3036                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3037                         expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3038                 },
3039                 _ => panic!("Unexpected event"),
3040         }
3041 }
3042
3043 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3044         // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3045         // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3046         // commitment transaction anymore.
3047         // To do this, we have the peer which will broadcast a revoked commitment transaction send
3048         // a number of update_fail/commitment_signed updates without ever sending the RAA in
3049         // response to our commitment_signed. This is somewhat misbehavior-y, though not
3050         // technically disallowed and we should probably handle it reasonably.
3051         // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3052         // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3053         // transactions:
3054         // * Once we move it out of our holding cell/add it, we will immediately include it in a
3055         //   commitment_signed (implying it will be in the latest remote commitment transaction).
3056         // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3057         //   and once they revoke the previous commitment transaction (allowing us to send a new
3058         //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3059         let chanmon_cfgs = create_chanmon_cfgs(3);
3060         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3061         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3062         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3063
3064         // Create some initial channels
3065         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3066         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3067
3068         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 });
3069         // Get the will-be-revoked local txn from nodes[2]
3070         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3071         assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3072         // Revoke the old state
3073         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3074
3075         let value = if use_dust {
3076                 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3077                 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3078                 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3079         } else { 3000000 };
3080
3081         let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3082         let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3083         let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3084
3085         assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash));
3086         expect_pending_htlcs_forwardable!(nodes[2]);
3087         check_added_monitors!(nodes[2], 1);
3088         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3089         assert!(updates.update_add_htlcs.is_empty());
3090         assert!(updates.update_fulfill_htlcs.is_empty());
3091         assert!(updates.update_fail_malformed_htlcs.is_empty());
3092         assert_eq!(updates.update_fail_htlcs.len(), 1);
3093         assert!(updates.update_fee.is_none());
3094         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3095         let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3096         // Drop the last RAA from 3 -> 2
3097
3098         assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash));
3099         expect_pending_htlcs_forwardable!(nodes[2]);
3100         check_added_monitors!(nodes[2], 1);
3101         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3102         assert!(updates.update_add_htlcs.is_empty());
3103         assert!(updates.update_fulfill_htlcs.is_empty());
3104         assert!(updates.update_fail_malformed_htlcs.is_empty());
3105         assert_eq!(updates.update_fail_htlcs.len(), 1);
3106         assert!(updates.update_fee.is_none());
3107         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3108         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3109         check_added_monitors!(nodes[1], 1);
3110         // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3111         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3112         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3113         check_added_monitors!(nodes[2], 1);
3114
3115         assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash));
3116         expect_pending_htlcs_forwardable!(nodes[2]);
3117         check_added_monitors!(nodes[2], 1);
3118         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3119         assert!(updates.update_add_htlcs.is_empty());
3120         assert!(updates.update_fulfill_htlcs.is_empty());
3121         assert!(updates.update_fail_malformed_htlcs.is_empty());
3122         assert_eq!(updates.update_fail_htlcs.len(), 1);
3123         assert!(updates.update_fee.is_none());
3124         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3125         // At this point first_payment_hash has dropped out of the latest two commitment
3126         // transactions that nodes[1] is tracking...
3127         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3128         check_added_monitors!(nodes[1], 1);
3129         // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3130         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3131         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3132         check_added_monitors!(nodes[2], 1);
3133
3134         // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3135         // on nodes[2]'s RAA.
3136         let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3137         nodes[1].node.send_payment(&route, fourth_payment_hash, &Some(fourth_payment_secret)).unwrap();
3138         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3139         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3140         check_added_monitors!(nodes[1], 0);
3141
3142         if deliver_bs_raa {
3143                 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3144                 // One monitor for the new revocation preimage, no second on as we won't generate a new
3145                 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3146                 check_added_monitors!(nodes[1], 1);
3147                 let events = nodes[1].node.get_and_clear_pending_events();
3148                 assert_eq!(events.len(), 1);
3149                 match events[0] {
3150                         Event::PendingHTLCsForwardable { .. } => { },
3151                         _ => panic!("Unexpected event"),
3152                 };
3153                 // Deliberately don't process the pending fail-back so they all fail back at once after
3154                 // block connection just like the !deliver_bs_raa case
3155         }
3156
3157         let mut failed_htlcs = HashSet::new();
3158         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3159
3160         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3161         check_added_monitors!(nodes[1], 1);
3162         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3163         assert!(ANTI_REORG_DELAY > PAYMENT_EXPIRY_BLOCKS); // We assume payments will also expire
3164
3165         let events = nodes[1].node.get_and_clear_pending_events();
3166         assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 4 });
3167         match events[0] {
3168                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3169                 _ => panic!("Unexepected event"),
3170         }
3171         match events[1] {
3172                 Event::PaymentPathFailed { ref payment_hash, .. } => {
3173                         assert_eq!(*payment_hash, fourth_payment_hash);
3174                 },
3175                 _ => panic!("Unexpected event"),
3176         }
3177         if !deliver_bs_raa {
3178                 match events[2] {
3179                         Event::PaymentFailed { ref payment_hash, .. } => {
3180                                 assert_eq!(*payment_hash, fourth_payment_hash);
3181                         },
3182                         _ => panic!("Unexpected event"),
3183                 }
3184                 match events[3] {
3185                         Event::PendingHTLCsForwardable { .. } => { },
3186                         _ => panic!("Unexpected event"),
3187                 };
3188         }
3189         nodes[1].node.process_pending_htlc_forwards();
3190         check_added_monitors!(nodes[1], 1);
3191
3192         let events = nodes[1].node.get_and_clear_pending_msg_events();
3193         assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3194         match events[if deliver_bs_raa { 1 } else { 0 }] {
3195                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3196                 _ => panic!("Unexpected event"),
3197         }
3198         match events[if deliver_bs_raa { 2 } else { 1 }] {
3199                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3200                         assert_eq!(channel_id, chan_2.2);
3201                         assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3202                 },
3203                 _ => panic!("Unexpected event"),
3204         }
3205         if deliver_bs_raa {
3206                 match events[0] {
3207                         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, .. } } => {
3208                                 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3209                                 assert_eq!(update_add_htlcs.len(), 1);
3210                                 assert!(update_fulfill_htlcs.is_empty());
3211                                 assert!(update_fail_htlcs.is_empty());
3212                                 assert!(update_fail_malformed_htlcs.is_empty());
3213                         },
3214                         _ => panic!("Unexpected event"),
3215                 }
3216         }
3217         match events[if deliver_bs_raa { 3 } else { 2 }] {
3218                 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, .. } } => {
3219                         assert!(update_add_htlcs.is_empty());
3220                         assert_eq!(update_fail_htlcs.len(), 3);
3221                         assert!(update_fulfill_htlcs.is_empty());
3222                         assert!(update_fail_malformed_htlcs.is_empty());
3223                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3224
3225                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3226                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3227                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3228
3229                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3230
3231                         let events = nodes[0].node.get_and_clear_pending_events();
3232                         assert_eq!(events.len(), 3);
3233                         match events[0] {
3234                                 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3235                                         assert!(failed_htlcs.insert(payment_hash.0));
3236                                         // If we delivered B's RAA we got an unknown preimage error, not something
3237                                         // that we should update our routing table for.
3238                                         if !deliver_bs_raa {
3239                                                 assert!(network_update.is_some());
3240                                         }
3241                                 },
3242                                 _ => panic!("Unexpected event"),
3243                         }
3244                         match events[1] {
3245                                 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3246                                         assert!(failed_htlcs.insert(payment_hash.0));
3247                                         assert!(network_update.is_some());
3248                                 },
3249                                 _ => panic!("Unexpected event"),
3250                         }
3251                         match events[2] {
3252                                 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3253                                         assert!(failed_htlcs.insert(payment_hash.0));
3254                                         assert!(network_update.is_some());
3255                                 },
3256                                 _ => panic!("Unexpected event"),
3257                         }
3258                 },
3259                 _ => panic!("Unexpected event"),
3260         }
3261
3262         assert!(failed_htlcs.contains(&first_payment_hash.0));
3263         assert!(failed_htlcs.contains(&second_payment_hash.0));
3264         assert!(failed_htlcs.contains(&third_payment_hash.0));
3265 }
3266
3267 #[test]
3268 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3269         do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3270         do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3271         do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3272         do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3273 }
3274
3275 #[test]
3276 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3277         do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3278         do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3279         do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3280         do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3281 }
3282
3283 #[test]
3284 fn fail_backward_pending_htlc_upon_channel_failure() {
3285         let chanmon_cfgs = create_chanmon_cfgs(2);
3286         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3287         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3288         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3289         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
3290
3291         // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3292         {
3293                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3294                 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
3295                 check_added_monitors!(nodes[0], 1);
3296
3297                 let payment_event = {
3298                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3299                         assert_eq!(events.len(), 1);
3300                         SendEvent::from_event(events.remove(0))
3301                 };
3302                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3303                 assert_eq!(payment_event.msgs.len(), 1);
3304         }
3305
3306         // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3307         let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3308         {
3309                 nodes[0].node.send_payment(&route, failed_payment_hash, &Some(failed_payment_secret)).unwrap();
3310                 check_added_monitors!(nodes[0], 0);
3311
3312                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3313         }
3314
3315         // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3316         {
3317                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3318
3319                 let secp_ctx = Secp256k1::new();
3320                 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3321                 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3322                 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &Some(payment_secret), current_height, &None).unwrap();
3323                 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3324                 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3325
3326                 // Send a 0-msat update_add_htlc to fail the channel.
3327                 let update_add_htlc = msgs::UpdateAddHTLC {
3328                         channel_id: chan.2,
3329                         htlc_id: 0,
3330                         amount_msat: 0,
3331                         payment_hash,
3332                         cltv_expiry,
3333                         onion_routing_packet,
3334                 };
3335                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3336         }
3337         let events = nodes[0].node.get_and_clear_pending_events();
3338         assert_eq!(events.len(), 2);
3339         // Check that Alice fails backward the pending HTLC from the second payment.
3340         match events[0] {
3341                 Event::PaymentPathFailed { payment_hash, .. } => {
3342                         assert_eq!(payment_hash, failed_payment_hash);
3343                 },
3344                 _ => panic!("Unexpected event"),
3345         }
3346         match events[1] {
3347                 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3348                         assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3349                 },
3350                 _ => panic!("Unexpected event {:?}", events[1]),
3351         }
3352         check_closed_broadcast!(nodes[0], true);
3353         check_added_monitors!(nodes[0], 1);
3354 }
3355
3356 #[test]
3357 fn test_htlc_ignore_latest_remote_commitment() {
3358         // Test that HTLC transactions spending the latest remote commitment transaction are simply
3359         // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3360         let chanmon_cfgs = create_chanmon_cfgs(2);
3361         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3362         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3363         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3364         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3365
3366         route_payment(&nodes[0], &[&nodes[1]], 10000000);
3367         nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3368         connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3369         check_closed_broadcast!(nodes[0], true);
3370         check_added_monitors!(nodes[0], 1);
3371         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
3372
3373         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3374         assert_eq!(node_txn.len(), 3);
3375         assert_eq!(node_txn[0], node_txn[1]);
3376
3377         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3378         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3379         check_closed_broadcast!(nodes[1], true);
3380         check_added_monitors!(nodes[1], 1);
3381         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3382
3383         // Duplicate the connect_block call since this may happen due to other listeners
3384         // registering new transactions
3385         header.prev_blockhash = header.block_hash();
3386         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[2].clone()]});
3387 }
3388
3389 #[test]
3390 fn test_force_close_fail_back() {
3391         // Check which HTLCs are failed-backwards on channel force-closure
3392         let chanmon_cfgs = create_chanmon_cfgs(3);
3393         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3394         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3395         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3396         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3397         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3398
3399         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3400
3401         let mut payment_event = {
3402                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
3403                 check_added_monitors!(nodes[0], 1);
3404
3405                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3406                 assert_eq!(events.len(), 1);
3407                 SendEvent::from_event(events.remove(0))
3408         };
3409
3410         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3411         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3412
3413         expect_pending_htlcs_forwardable!(nodes[1]);
3414
3415         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3416         assert_eq!(events_2.len(), 1);
3417         payment_event = SendEvent::from_event(events_2.remove(0));
3418         assert_eq!(payment_event.msgs.len(), 1);
3419
3420         check_added_monitors!(nodes[1], 1);
3421         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3422         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3423         check_added_monitors!(nodes[2], 1);
3424         let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3425
3426         // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3427         // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3428         // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3429
3430         nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3431         check_closed_broadcast!(nodes[2], true);
3432         check_added_monitors!(nodes[2], 1);
3433         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
3434         let tx = {
3435                 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3436                 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3437                 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3438                 // back to nodes[1] upon timeout otherwise.
3439                 assert_eq!(node_txn.len(), 1);
3440                 node_txn.remove(0)
3441         };
3442
3443         mine_transaction(&nodes[1], &tx);
3444
3445         // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3446         check_closed_broadcast!(nodes[1], true);
3447         check_added_monitors!(nodes[1], 1);
3448         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3449
3450         // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3451         {
3452                 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3453                         .provide_payment_preimage(&our_payment_hash, &our_payment_preimage, &node_cfgs[2].tx_broadcaster, &node_cfgs[2].fee_estimator, &node_cfgs[2].logger);
3454         }
3455         mine_transaction(&nodes[2], &tx);
3456         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3457         assert_eq!(node_txn.len(), 1);
3458         assert_eq!(node_txn[0].input.len(), 1);
3459         assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3460         assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3461         assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3462
3463         check_spends!(node_txn[0], tx);
3464 }
3465
3466 #[test]
3467 fn test_dup_events_on_peer_disconnect() {
3468         // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3469         // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3470         // as we used to generate the event immediately upon receipt of the payment preimage in the
3471         // update_fulfill_htlc message.
3472
3473         let chanmon_cfgs = create_chanmon_cfgs(2);
3474         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3475         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3476         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3477         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3478
3479         let payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 1000000).0;
3480
3481         assert!(nodes[1].node.claim_funds(payment_preimage));
3482         check_added_monitors!(nodes[1], 1);
3483         let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3484         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3485         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
3486
3487         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3488         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3489
3490         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3491         expect_payment_path_successful!(nodes[0]);
3492 }
3493
3494 #[test]
3495 fn test_peer_disconnected_before_funding_broadcasted() {
3496         // Test that channels are closed with `ClosureReason::DisconnectedPeer` if the peer disconnects
3497         // before the funding transaction has been broadcasted.
3498         let chanmon_cfgs = create_chanmon_cfgs(2);
3499         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3500         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3501         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3502
3503         // Open a channel between `nodes[0]` and `nodes[1]`, for which the funding transaction is never
3504         // broadcasted, even though it's created by `nodes[0]`.
3505         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();
3506         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
3507         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
3508         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
3509         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
3510
3511         let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
3512         assert_eq!(temporary_channel_id, expected_temporary_channel_id);
3513
3514         assert!(nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
3515
3516         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
3517         assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
3518
3519         // Even though the funding transaction is created by `nodes[0]`, the `FundingCreated` msg is
3520         // never sent to `nodes[1]`, and therefore the tx is never signed by either party nor
3521         // broadcasted.
3522         {
3523                 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
3524         }
3525
3526         // Ensure that the channel is closed with `ClosureReason::DisconnectedPeer` when the peers are
3527         // disconnected before the funding transaction was broadcasted.
3528         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3529         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3530
3531         check_closed_event!(nodes[0], 1, ClosureReason::DisconnectedPeer);
3532         check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
3533 }
3534
3535 #[test]
3536 fn test_simple_peer_disconnect() {
3537         // Test that we can reconnect when there are no lost messages
3538         let chanmon_cfgs = create_chanmon_cfgs(3);
3539         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3540         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3541         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3542         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3543         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3544
3545         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3546         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3547         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3548
3549         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3550         let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3551         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3552         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3553
3554         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3555         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3556         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3557
3558         let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3559         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3560         let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3561         let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3562
3563         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3564         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3565
3566         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3567         fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3568
3569         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3570         {
3571                 let events = nodes[0].node.get_and_clear_pending_events();
3572                 assert_eq!(events.len(), 3);
3573                 match events[0] {
3574                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3575                                 assert_eq!(payment_preimage, payment_preimage_3);
3576                                 assert_eq!(payment_hash, payment_hash_3);
3577                         },
3578                         _ => panic!("Unexpected event"),
3579                 }
3580                 match events[1] {
3581                         Event::PaymentPathFailed { payment_hash, rejected_by_dest, .. } => {
3582                                 assert_eq!(payment_hash, payment_hash_5);
3583                                 assert!(rejected_by_dest);
3584                         },
3585                         _ => panic!("Unexpected event"),
3586                 }
3587                 match events[2] {
3588                         Event::PaymentPathSuccessful { .. } => {},
3589                         _ => panic!("Unexpected event"),
3590                 }
3591         }
3592
3593         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3594         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3595 }
3596
3597 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3598         // Test that we can reconnect when in-flight HTLC updates get dropped
3599         let chanmon_cfgs = create_chanmon_cfgs(2);
3600         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3601         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3602         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3603
3604         let mut as_funding_locked = None;
3605         if messages_delivered == 0 {
3606                 let (funding_locked, _, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3607                 as_funding_locked = Some(funding_locked);
3608                 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
3609                 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3610                 // it before the channel_reestablish message.
3611         } else {
3612                 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3613         }
3614
3615         let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3616
3617         let payment_event = {
3618                 nodes[0].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)).unwrap();
3619                 check_added_monitors!(nodes[0], 1);
3620
3621                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3622                 assert_eq!(events.len(), 1);
3623                 SendEvent::from_event(events.remove(0))
3624         };
3625         assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3626
3627         if messages_delivered < 2 {
3628                 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3629         } else {
3630                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3631                 if messages_delivered >= 3 {
3632                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3633                         check_added_monitors!(nodes[1], 1);
3634                         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3635
3636                         if messages_delivered >= 4 {
3637                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3638                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3639                                 check_added_monitors!(nodes[0], 1);
3640
3641                                 if messages_delivered >= 5 {
3642                                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3643                                         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3644                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3645                                         check_added_monitors!(nodes[0], 1);
3646
3647                                         if messages_delivered >= 6 {
3648                                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3649                                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3650                                                 check_added_monitors!(nodes[1], 1);
3651                                         }
3652                                 }
3653                         }
3654                 }
3655         }
3656
3657         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3658         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3659         if messages_delivered < 3 {
3660                 if simulate_broken_lnd {
3661                         // lnd has a long-standing bug where they send a funding_locked prior to a
3662                         // channel_reestablish if you reconnect prior to funding_locked time.
3663                         //
3664                         // Here we simulate that behavior, delivering a funding_locked immediately on
3665                         // reconnect. Note that we don't bother skipping the now-duplicate funding_locked sent
3666                         // in `reconnect_nodes` but we currently don't fail based on that.
3667                         //
3668                         // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3669                         nodes[1].node.handle_funding_locked(&nodes[0].node.get_our_node_id(), &as_funding_locked.as_ref().unwrap().0);
3670                 }
3671                 // Even if the funding_locked messages get exchanged, as long as nothing further was
3672                 // received on either side, both sides will need to resend them.
3673                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3674         } else if messages_delivered == 3 {
3675                 // nodes[0] still wants its RAA + commitment_signed
3676                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3677         } else if messages_delivered == 4 {
3678                 // nodes[0] still wants its commitment_signed
3679                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3680         } else if messages_delivered == 5 {
3681                 // nodes[1] still wants its final RAA
3682                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3683         } else if messages_delivered == 6 {
3684                 // Everything was delivered...
3685                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3686         }
3687
3688         let events_1 = nodes[1].node.get_and_clear_pending_events();
3689         assert_eq!(events_1.len(), 1);
3690         match events_1[0] {
3691                 Event::PendingHTLCsForwardable { .. } => { },
3692                 _ => panic!("Unexpected event"),
3693         };
3694
3695         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3696         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3697         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3698
3699         nodes[1].node.process_pending_htlc_forwards();
3700
3701         let events_2 = nodes[1].node.get_and_clear_pending_events();
3702         assert_eq!(events_2.len(), 1);
3703         match events_2[0] {
3704                 Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
3705                         assert_eq!(payment_hash_1, *payment_hash);
3706                         assert_eq!(amt, 1000000);
3707                         match &purpose {
3708                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3709                                         assert!(payment_preimage.is_none());
3710                                         assert_eq!(payment_secret_1, *payment_secret);
3711                                 },
3712                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
3713                         }
3714                 },
3715                 _ => panic!("Unexpected event"),
3716         }
3717
3718         nodes[1].node.claim_funds(payment_preimage_1);
3719         check_added_monitors!(nodes[1], 1);
3720
3721         let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3722         assert_eq!(events_3.len(), 1);
3723         let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3724                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3725                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3726                         assert!(updates.update_add_htlcs.is_empty());
3727                         assert!(updates.update_fail_htlcs.is_empty());
3728                         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3729                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3730                         assert!(updates.update_fee.is_none());
3731                         (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3732                 },
3733                 _ => panic!("Unexpected event"),
3734         };
3735
3736         if messages_delivered >= 1 {
3737                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3738
3739                 let events_4 = nodes[0].node.get_and_clear_pending_events();
3740                 assert_eq!(events_4.len(), 1);
3741                 match events_4[0] {
3742                         Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3743                                 assert_eq!(payment_preimage_1, *payment_preimage);
3744                                 assert_eq!(payment_hash_1, *payment_hash);
3745                         },
3746                         _ => panic!("Unexpected event"),
3747                 }
3748
3749                 if messages_delivered >= 2 {
3750                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3751                         check_added_monitors!(nodes[0], 1);
3752                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3753
3754                         if messages_delivered >= 3 {
3755                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3756                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3757                                 check_added_monitors!(nodes[1], 1);
3758
3759                                 if messages_delivered >= 4 {
3760                                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3761                                         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3762                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3763                                         check_added_monitors!(nodes[1], 1);
3764
3765                                         if messages_delivered >= 5 {
3766                                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3767                                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3768                                                 check_added_monitors!(nodes[0], 1);
3769                                         }
3770                                 }
3771                         }
3772                 }
3773         }
3774
3775         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3776         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3777         if messages_delivered < 2 {
3778                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3779                 if messages_delivered < 1 {
3780                         expect_payment_sent!(nodes[0], payment_preimage_1);
3781                 } else {
3782                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3783                 }
3784         } else if messages_delivered == 2 {
3785                 // nodes[0] still wants its RAA + commitment_signed
3786                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3787         } else if messages_delivered == 3 {
3788                 // nodes[0] still wants its commitment_signed
3789                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3790         } else if messages_delivered == 4 {
3791                 // nodes[1] still wants its final RAA
3792                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3793         } else if messages_delivered == 5 {
3794                 // Everything was delivered...
3795                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3796         }
3797
3798         if messages_delivered == 1 || messages_delivered == 2 {
3799                 expect_payment_path_successful!(nodes[0]);
3800         }
3801
3802         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3803         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3804         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3805
3806         if messages_delivered > 2 {
3807                 expect_payment_path_successful!(nodes[0]);
3808         }
3809
3810         // Channel should still work fine...
3811         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3812         let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3813         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3814 }
3815
3816 #[test]
3817 fn test_drop_messages_peer_disconnect_a() {
3818         do_test_drop_messages_peer_disconnect(0, true);
3819         do_test_drop_messages_peer_disconnect(0, false);
3820         do_test_drop_messages_peer_disconnect(1, false);
3821         do_test_drop_messages_peer_disconnect(2, false);
3822 }
3823
3824 #[test]
3825 fn test_drop_messages_peer_disconnect_b() {
3826         do_test_drop_messages_peer_disconnect(3, false);
3827         do_test_drop_messages_peer_disconnect(4, false);
3828         do_test_drop_messages_peer_disconnect(5, false);
3829         do_test_drop_messages_peer_disconnect(6, false);
3830 }
3831
3832 #[test]
3833 fn test_funding_peer_disconnect() {
3834         // Test that we can lock in our funding tx while disconnected
3835         let chanmon_cfgs = create_chanmon_cfgs(2);
3836         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3837         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3838         let persister: test_utils::TestPersister;
3839         let new_chain_monitor: test_utils::TestChainMonitor;
3840         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
3841         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3842         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3843
3844         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3845         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3846
3847         confirm_transaction(&nodes[0], &tx);
3848         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3849         assert!(events_1.is_empty());
3850
3851         reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3852
3853         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3854         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3855
3856         confirm_transaction(&nodes[1], &tx);
3857         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3858         assert!(events_2.is_empty());
3859
3860         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
3861         let as_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
3862         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
3863         let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
3864
3865         // nodes[0] hasn't yet received a funding_locked, so it only sends that on reconnect.
3866         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
3867         let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3868         assert_eq!(events_3.len(), 1);
3869         let as_funding_locked = match events_3[0] {
3870                 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3871                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3872                         msg.clone()
3873                 },
3874                 _ => panic!("Unexpected event {:?}", events_3[0]),
3875         };
3876
3877         // nodes[1] received nodes[0]'s funding_locked on the first reconnect above, so it should send
3878         // announcement_signatures as well as channel_update.
3879         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reestablish);
3880         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3881         assert_eq!(events_4.len(), 3);
3882         let chan_id;
3883         let bs_funding_locked = match events_4[0] {
3884                 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3885                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3886                         chan_id = msg.channel_id;
3887                         msg.clone()
3888                 },
3889                 _ => panic!("Unexpected event {:?}", events_4[0]),
3890         };
3891         let bs_announcement_sigs = match events_4[1] {
3892                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3893                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3894                         msg.clone()
3895                 },
3896                 _ => panic!("Unexpected event {:?}", events_4[1]),
3897         };
3898         match events_4[2] {
3899                 MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } => {
3900                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3901                 },
3902                 _ => panic!("Unexpected event {:?}", events_4[2]),
3903         }
3904
3905         // Re-deliver nodes[0]'s funding_locked, which nodes[1] can safely ignore. It currently
3906         // generates a duplicative private channel_update
3907         nodes[1].node.handle_funding_locked(&nodes[0].node.get_our_node_id(), &as_funding_locked);
3908         let events_5 = nodes[1].node.get_and_clear_pending_msg_events();
3909         assert_eq!(events_5.len(), 1);
3910         match events_5[0] {
3911                 MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } => {
3912                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3913                 },
3914                 _ => panic!("Unexpected event {:?}", events_5[0]),
3915         };
3916
3917         // When we deliver nodes[1]'s funding_locked, however, nodes[0] will generate its
3918         // announcement_signatures.
3919         nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &bs_funding_locked);
3920         let events_6 = nodes[0].node.get_and_clear_pending_msg_events();
3921         assert_eq!(events_6.len(), 1);
3922         let as_announcement_sigs = match events_6[0] {
3923                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3924                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3925                         msg.clone()
3926                 },
3927                 _ => panic!("Unexpected event {:?}", events_6[0]),
3928         };
3929
3930         // When we deliver nodes[1]'s announcement_signatures to nodes[0], nodes[0] should immediately
3931         // broadcast the channel announcement globally, as well as re-send its (now-public)
3932         // channel_update.
3933         nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3934         let events_7 = nodes[0].node.get_and_clear_pending_msg_events();
3935         assert_eq!(events_7.len(), 1);
3936         let (chan_announcement, as_update) = match events_7[0] {
3937                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3938                         (msg.clone(), update_msg.clone())
3939                 },
3940                 _ => panic!("Unexpected event {:?}", events_7[0]),
3941         };
3942
3943         // Finally, deliver nodes[0]'s announcement_signatures to nodes[1] and make sure it creates the
3944         // same channel_announcement.
3945         nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3946         let events_8 = nodes[1].node.get_and_clear_pending_msg_events();
3947         assert_eq!(events_8.len(), 1);
3948         let bs_update = match events_8[0] {
3949                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3950                         assert_eq!(*msg, chan_announcement);
3951                         update_msg.clone()
3952                 },
3953                 _ => panic!("Unexpected event {:?}", events_8[0]),
3954         };
3955
3956         // Provide the channel announcement and public updates to the network graph
3957         nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).unwrap();
3958         nodes[0].net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
3959         nodes[0].net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
3960
3961         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3962         let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3963         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
3964
3965         // Check that after deserialization and reconnection we can still generate an identical
3966         // channel_announcement from the cached signatures.
3967         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3968
3969         let nodes_0_serialized = nodes[0].node.encode();
3970         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
3971         get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
3972
3973         persister = test_utils::TestPersister::new();
3974         let keys_manager = &chanmon_cfgs[0].keys_manager;
3975         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);
3976         nodes[0].chain_monitor = &new_chain_monitor;
3977         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
3978         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
3979                 &mut chan_0_monitor_read, keys_manager).unwrap();
3980         assert!(chan_0_monitor_read.is_empty());
3981
3982         let mut nodes_0_read = &nodes_0_serialized[..];
3983         let (_, nodes_0_deserialized_tmp) = {
3984                 let mut channel_monitors = HashMap::new();
3985                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
3986                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
3987                         default_config: UserConfig::default(),
3988                         keys_manager,
3989                         fee_estimator: node_cfgs[0].fee_estimator,
3990                         chain_monitor: nodes[0].chain_monitor,
3991                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
3992                         logger: nodes[0].logger,
3993                         channel_monitors,
3994                 }).unwrap()
3995         };
3996         nodes_0_deserialized = nodes_0_deserialized_tmp;
3997         assert!(nodes_0_read.is_empty());
3998
3999         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4000         nodes[0].node = &nodes_0_deserialized;
4001         check_added_monitors!(nodes[0], 1);
4002
4003         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4004
4005         // The channel announcement should be re-generated exactly by broadcast_node_announcement.
4006         nodes[0].node.broadcast_node_announcement([0, 0, 0], [0; 32], Vec::new());
4007         let msgs = nodes[0].node.get_and_clear_pending_msg_events();
4008         let mut found_announcement = false;
4009         for event in msgs.iter() {
4010                 match event {
4011                         MessageSendEvent::BroadcastChannelAnnouncement { ref msg, .. } => {
4012                                 if *msg == chan_announcement { found_announcement = true; }
4013                         },
4014                         MessageSendEvent::BroadcastNodeAnnouncement { .. } => {},
4015                         _ => panic!("Unexpected event"),
4016                 }
4017         }
4018         assert!(found_announcement);
4019 }
4020
4021 #[test]
4022 fn test_funding_locked_without_best_block_updated() {
4023         // Previously, if we were offline when a funding transaction was locked in, and then we came
4024         // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
4025         // generate a funding_locked until a later best_block_updated. This tests that we generate the
4026         // funding_locked immediately instead.
4027         let chanmon_cfgs = create_chanmon_cfgs(2);
4028         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4029         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4030         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4031         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
4032
4033         let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
4034
4035         let conf_height = nodes[0].best_block_info().1 + 1;
4036         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
4037         let block_txn = [funding_tx];
4038         let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
4039         let conf_block_header = nodes[0].get_block_header(conf_height);
4040         nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
4041
4042         // Ensure nodes[0] generates a funding_locked after the transactions_confirmed
4043         let as_funding_locked = get_event_msg!(nodes[0], MessageSendEvent::SendFundingLocked, nodes[1].node.get_our_node_id());
4044         nodes[1].node.handle_funding_locked(&nodes[0].node.get_our_node_id(), &as_funding_locked);
4045 }
4046
4047 #[test]
4048 fn test_drop_messages_peer_disconnect_dual_htlc() {
4049         // Test that we can handle reconnecting when both sides of a channel have pending
4050         // commitment_updates when we disconnect.
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         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4056
4057         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4058
4059         // Now try to send a second payment which will fail to send
4060         let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
4061         nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
4062         check_added_monitors!(nodes[0], 1);
4063
4064         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
4065         assert_eq!(events_1.len(), 1);
4066         match events_1[0] {
4067                 MessageSendEvent::UpdateHTLCs { .. } => {},
4068                 _ => panic!("Unexpected event"),
4069         }
4070
4071         assert!(nodes[1].node.claim_funds(payment_preimage_1));
4072         check_added_monitors!(nodes[1], 1);
4073
4074         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
4075         assert_eq!(events_2.len(), 1);
4076         match events_2[0] {
4077                 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 } } => {
4078                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
4079                         assert!(update_add_htlcs.is_empty());
4080                         assert_eq!(update_fulfill_htlcs.len(), 1);
4081                         assert!(update_fail_htlcs.is_empty());
4082                         assert!(update_fail_malformed_htlcs.is_empty());
4083                         assert!(update_fee.is_none());
4084
4085                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
4086                         let events_3 = nodes[0].node.get_and_clear_pending_events();
4087                         assert_eq!(events_3.len(), 1);
4088                         match events_3[0] {
4089                                 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4090                                         assert_eq!(*payment_preimage, payment_preimage_1);
4091                                         assert_eq!(*payment_hash, payment_hash_1);
4092                                 },
4093                                 _ => panic!("Unexpected event"),
4094                         }
4095
4096                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
4097                         let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4098                         // No commitment_signed so get_event_msg's assert(len == 1) passes
4099                         check_added_monitors!(nodes[0], 1);
4100                 },
4101                 _ => panic!("Unexpected event"),
4102         }
4103
4104         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
4105         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4106
4107         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4108         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4109         assert_eq!(reestablish_1.len(), 1);
4110         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4111         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4112         assert_eq!(reestablish_2.len(), 1);
4113
4114         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4115         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4116         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4117         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4118
4119         assert!(as_resp.0.is_none());
4120         assert!(bs_resp.0.is_none());
4121
4122         assert!(bs_resp.1.is_none());
4123         assert!(bs_resp.2.is_none());
4124
4125         assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4126
4127         assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4128         assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4129         assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4130         assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4131         assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4132         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4133         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4134         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4135         // No commitment_signed so get_event_msg's assert(len == 1) passes
4136         check_added_monitors!(nodes[1], 1);
4137
4138         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4139         let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4140         assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4141         assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4142         assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4143         assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4144         assert!(bs_second_commitment_signed.update_fee.is_none());
4145         check_added_monitors!(nodes[1], 1);
4146
4147         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4148         let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4149         assert!(as_commitment_signed.update_add_htlcs.is_empty());
4150         assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4151         assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4152         assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4153         assert!(as_commitment_signed.update_fee.is_none());
4154         check_added_monitors!(nodes[0], 1);
4155
4156         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4157         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4158         // No commitment_signed so get_event_msg's assert(len == 1) passes
4159         check_added_monitors!(nodes[0], 1);
4160
4161         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4162         let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4163         // No commitment_signed so get_event_msg's assert(len == 1) passes
4164         check_added_monitors!(nodes[1], 1);
4165
4166         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4167         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4168         check_added_monitors!(nodes[1], 1);
4169
4170         expect_pending_htlcs_forwardable!(nodes[1]);
4171
4172         let events_5 = nodes[1].node.get_and_clear_pending_events();
4173         assert_eq!(events_5.len(), 1);
4174         match events_5[0] {
4175                 Event::PaymentReceived { ref payment_hash, ref purpose, .. } => {
4176                         assert_eq!(payment_hash_2, *payment_hash);
4177                         match &purpose {
4178                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4179                                         assert!(payment_preimage.is_none());
4180                                         assert_eq!(payment_secret_2, *payment_secret);
4181                                 },
4182                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
4183                         }
4184                 },
4185                 _ => panic!("Unexpected event"),
4186         }
4187
4188         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4189         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4190         check_added_monitors!(nodes[0], 1);
4191
4192         expect_payment_path_successful!(nodes[0]);
4193         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4194 }
4195
4196 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4197         // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4198         // to avoid our counterparty failing the channel.
4199         let chanmon_cfgs = create_chanmon_cfgs(2);
4200         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4201         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4202         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4203
4204         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4205
4206         let our_payment_hash = if send_partial_mpp {
4207                 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4208                 // Use the utility function send_payment_along_path to send the payment with MPP data which
4209                 // indicates there are more HTLCs coming.
4210                 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.
4211                 let payment_id = PaymentId([42; 32]);
4212                 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();
4213                 check_added_monitors!(nodes[0], 1);
4214                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4215                 assert_eq!(events.len(), 1);
4216                 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4217                 // hop should *not* yet generate any PaymentReceived event(s).
4218                 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4219                 our_payment_hash
4220         } else {
4221                 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4222         };
4223
4224         let mut block = Block {
4225                 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
4226                 txdata: vec![],
4227         };
4228         connect_block(&nodes[0], &block);
4229         connect_block(&nodes[1], &block);
4230         let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4231         for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4232                 block.header.prev_blockhash = block.block_hash();
4233                 connect_block(&nodes[0], &block);
4234                 connect_block(&nodes[1], &block);
4235         }
4236
4237         expect_pending_htlcs_forwardable!(nodes[1]);
4238
4239         check_added_monitors!(nodes[1], 1);
4240         let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4241         assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4242         assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4243         assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4244         assert!(htlc_timeout_updates.update_fee.is_none());
4245
4246         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4247         commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4248         // 100_000 msat as u64, followed by the height at which we failed back above
4249         let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
4250         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(block_count - 1));
4251         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4252 }
4253
4254 #[test]
4255 fn test_htlc_timeout() {
4256         do_test_htlc_timeout(true);
4257         do_test_htlc_timeout(false);
4258 }
4259
4260 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4261         // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4262         let chanmon_cfgs = create_chanmon_cfgs(3);
4263         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4264         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4265         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4266         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4267         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4268
4269         // Make sure all nodes are at the same starting height
4270         connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4271         connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4272         connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4273
4274         // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4275         let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4276         {
4277                 nodes[1].node.send_payment(&route, first_payment_hash, &Some(first_payment_secret)).unwrap();
4278         }
4279         assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4280         check_added_monitors!(nodes[1], 1);
4281
4282         // Now attempt to route a second payment, which should be placed in the holding cell
4283         let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4284         let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4285         sending_node.node.send_payment(&route, second_payment_hash, &Some(second_payment_secret)).unwrap();
4286         if forwarded_htlc {
4287                 check_added_monitors!(nodes[0], 1);
4288                 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4289                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4290                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4291                 expect_pending_htlcs_forwardable!(nodes[1]);
4292         }
4293         check_added_monitors!(nodes[1], 0);
4294
4295         connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4296         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4297         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4298         connect_blocks(&nodes[1], 1);
4299
4300         if forwarded_htlc {
4301                 expect_pending_htlcs_forwardable!(nodes[1]);
4302                 check_added_monitors!(nodes[1], 1);
4303                 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4304                 assert_eq!(fail_commit.len(), 1);
4305                 match fail_commit[0] {
4306                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4307                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4308                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4309                         },
4310                         _ => unreachable!(),
4311                 }
4312                 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4313         } else {
4314                 let events = nodes[1].node.get_and_clear_pending_events();
4315                 assert_eq!(events.len(), 2);
4316                 if let Event::PaymentPathFailed { ref payment_hash, .. } = events[0] {
4317                         assert_eq!(*payment_hash, second_payment_hash);
4318                 } else { panic!("Unexpected event"); }
4319                 if let Event::PaymentFailed { ref payment_hash, .. } = events[1] {
4320                         assert_eq!(*payment_hash, second_payment_hash);
4321                 } else { panic!("Unexpected event"); }
4322         }
4323 }
4324
4325 #[test]
4326 fn test_holding_cell_htlc_add_timeouts() {
4327         do_test_holding_cell_htlc_add_timeouts(false);
4328         do_test_holding_cell_htlc_add_timeouts(true);
4329 }
4330
4331 #[test]
4332 fn test_no_txn_manager_serialize_deserialize() {
4333         let chanmon_cfgs = create_chanmon_cfgs(2);
4334         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4335         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4336         let logger: test_utils::TestLogger;
4337         let fee_estimator: test_utils::TestFeeEstimator;
4338         let persister: test_utils::TestPersister;
4339         let new_chain_monitor: test_utils::TestChainMonitor;
4340         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4341         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4342
4343         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
4344
4345         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4346
4347         let nodes_0_serialized = nodes[0].node.encode();
4348         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4349         get_monitor!(nodes[0], OutPoint { txid: tx.txid(), index: 0 }.to_channel_id())
4350                 .write(&mut chan_0_monitor_serialized).unwrap();
4351
4352         logger = test_utils::TestLogger::new();
4353         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4354         persister = test_utils::TestPersister::new();
4355         let keys_manager = &chanmon_cfgs[0].keys_manager;
4356         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4357         nodes[0].chain_monitor = &new_chain_monitor;
4358         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4359         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4360                 &mut chan_0_monitor_read, keys_manager).unwrap();
4361         assert!(chan_0_monitor_read.is_empty());
4362
4363         let mut nodes_0_read = &nodes_0_serialized[..];
4364         let config = UserConfig::default();
4365         let (_, nodes_0_deserialized_tmp) = {
4366                 let mut channel_monitors = HashMap::new();
4367                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4368                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4369                         default_config: config,
4370                         keys_manager,
4371                         fee_estimator: &fee_estimator,
4372                         chain_monitor: nodes[0].chain_monitor,
4373                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4374                         logger: &logger,
4375                         channel_monitors,
4376                 }).unwrap()
4377         };
4378         nodes_0_deserialized = nodes_0_deserialized_tmp;
4379         assert!(nodes_0_read.is_empty());
4380
4381         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4382         nodes[0].node = &nodes_0_deserialized;
4383         assert_eq!(nodes[0].node.list_channels().len(), 1);
4384         check_added_monitors!(nodes[0], 1);
4385
4386         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4387         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4388         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4389         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4390
4391         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4392         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4393         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4394         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4395
4396         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4397         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4398         for node in nodes.iter() {
4399                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4400                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4401                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4402         }
4403
4404         send_payment(&nodes[0], &[&nodes[1]], 1000000);
4405 }
4406
4407 #[test]
4408 fn test_manager_serialize_deserialize_events() {
4409         // This test makes sure the events field in ChannelManager survives de/serialization
4410         let chanmon_cfgs = create_chanmon_cfgs(2);
4411         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4412         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4413         let fee_estimator: test_utils::TestFeeEstimator;
4414         let persister: test_utils::TestPersister;
4415         let logger: test_utils::TestLogger;
4416         let new_chain_monitor: test_utils::TestChainMonitor;
4417         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4418         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4419
4420         // Start creating a channel, but stop right before broadcasting the funding transaction
4421         let channel_value = 100000;
4422         let push_msat = 10001;
4423         let a_flags = InitFeatures::known();
4424         let b_flags = InitFeatures::known();
4425         let node_a = nodes.remove(0);
4426         let node_b = nodes.remove(0);
4427         node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
4428         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()));
4429         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()));
4430
4431         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, &node_b.node.get_our_node_id(), channel_value, 42);
4432
4433         node_a.node.funding_transaction_generated(&temporary_channel_id, &node_b.node.get_our_node_id(), tx.clone()).unwrap();
4434         check_added_monitors!(node_a, 0);
4435
4436         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()));
4437         {
4438                 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
4439                 assert_eq!(added_monitors.len(), 1);
4440                 assert_eq!(added_monitors[0].0, funding_output);
4441                 added_monitors.clear();
4442         }
4443
4444         let bs_funding_signed = get_event_msg!(node_b, MessageSendEvent::SendFundingSigned, node_a.node.get_our_node_id());
4445         node_a.node.handle_funding_signed(&node_b.node.get_our_node_id(), &bs_funding_signed);
4446         {
4447                 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
4448                 assert_eq!(added_monitors.len(), 1);
4449                 assert_eq!(added_monitors[0].0, funding_output);
4450                 added_monitors.clear();
4451         }
4452         // Normally, this is where node_a would broadcast the funding transaction, but the test de/serializes first instead
4453
4454         nodes.push(node_a);
4455         nodes.push(node_b);
4456
4457         // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4458         let nodes_0_serialized = nodes[0].node.encode();
4459         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4460         get_monitor!(nodes[0], bs_funding_signed.channel_id).write(&mut chan_0_monitor_serialized).unwrap();
4461
4462         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4463         logger = test_utils::TestLogger::new();
4464         persister = test_utils::TestPersister::new();
4465         let keys_manager = &chanmon_cfgs[0].keys_manager;
4466         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4467         nodes[0].chain_monitor = &new_chain_monitor;
4468         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4469         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4470                 &mut chan_0_monitor_read, keys_manager).unwrap();
4471         assert!(chan_0_monitor_read.is_empty());
4472
4473         let mut nodes_0_read = &nodes_0_serialized[..];
4474         let config = UserConfig::default();
4475         let (_, nodes_0_deserialized_tmp) = {
4476                 let mut channel_monitors = HashMap::new();
4477                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4478                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4479                         default_config: config,
4480                         keys_manager,
4481                         fee_estimator: &fee_estimator,
4482                         chain_monitor: nodes[0].chain_monitor,
4483                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4484                         logger: &logger,
4485                         channel_monitors,
4486                 }).unwrap()
4487         };
4488         nodes_0_deserialized = nodes_0_deserialized_tmp;
4489         assert!(nodes_0_read.is_empty());
4490
4491         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4492
4493         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4494         nodes[0].node = &nodes_0_deserialized;
4495
4496         // After deserializing, make sure the funding_transaction is still held by the channel manager
4497         let events_4 = nodes[0].node.get_and_clear_pending_events();
4498         assert_eq!(events_4.len(), 0);
4499         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
4500         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
4501
4502         // Make sure the channel is functioning as though the de/serialization never happened
4503         assert_eq!(nodes[0].node.list_channels().len(), 1);
4504         check_added_monitors!(nodes[0], 1);
4505
4506         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4507         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4508         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4509         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4510
4511         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4512         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4513         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4514         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4515
4516         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4517         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4518         for node in nodes.iter() {
4519                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4520                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4521                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4522         }
4523
4524         send_payment(&nodes[0], &[&nodes[1]], 1000000);
4525 }
4526
4527 #[test]
4528 fn test_simple_manager_serialize_deserialize() {
4529         let chanmon_cfgs = create_chanmon_cfgs(2);
4530         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4531         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4532         let logger: test_utils::TestLogger;
4533         let fee_estimator: test_utils::TestFeeEstimator;
4534         let persister: test_utils::TestPersister;
4535         let new_chain_monitor: test_utils::TestChainMonitor;
4536         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4537         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4538         let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
4539
4540         let (our_payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4541         let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4542
4543         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4544
4545         let nodes_0_serialized = nodes[0].node.encode();
4546         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4547         get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
4548
4549         logger = test_utils::TestLogger::new();
4550         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4551         persister = test_utils::TestPersister::new();
4552         let keys_manager = &chanmon_cfgs[0].keys_manager;
4553         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4554         nodes[0].chain_monitor = &new_chain_monitor;
4555         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4556         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4557                 &mut chan_0_monitor_read, keys_manager).unwrap();
4558         assert!(chan_0_monitor_read.is_empty());
4559
4560         let mut nodes_0_read = &nodes_0_serialized[..];
4561         let (_, nodes_0_deserialized_tmp) = {
4562                 let mut channel_monitors = HashMap::new();
4563                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4564                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4565                         default_config: UserConfig::default(),
4566                         keys_manager,
4567                         fee_estimator: &fee_estimator,
4568                         chain_monitor: nodes[0].chain_monitor,
4569                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4570                         logger: &logger,
4571                         channel_monitors,
4572                 }).unwrap()
4573         };
4574         nodes_0_deserialized = nodes_0_deserialized_tmp;
4575         assert!(nodes_0_read.is_empty());
4576
4577         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4578         nodes[0].node = &nodes_0_deserialized;
4579         check_added_monitors!(nodes[0], 1);
4580
4581         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4582
4583         fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4584         claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
4585 }
4586
4587 #[test]
4588 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4589         // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4590         let chanmon_cfgs = create_chanmon_cfgs(4);
4591         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4592         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4593         let logger: test_utils::TestLogger;
4594         let fee_estimator: test_utils::TestFeeEstimator;
4595         let persister: test_utils::TestPersister;
4596         let new_chain_monitor: test_utils::TestChainMonitor;
4597         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4598         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4599         let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
4600         let chan_id_2 = create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known()).2;
4601         let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
4602
4603         let mut node_0_stale_monitors_serialized = Vec::new();
4604         for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4605                 let mut writer = test_utils::TestVecWriter(Vec::new());
4606                 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4607                 node_0_stale_monitors_serialized.push(writer.0);
4608         }
4609
4610         let (our_payment_preimage, _, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4611
4612         // Serialize the ChannelManager here, but the monitor we keep up-to-date
4613         let nodes_0_serialized = nodes[0].node.encode();
4614
4615         route_payment(&nodes[0], &[&nodes[3]], 1000000);
4616         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4617         nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4618         nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4619
4620         // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4621         // nodes[3])
4622         let mut node_0_monitors_serialized = Vec::new();
4623         for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4624                 let mut writer = test_utils::TestVecWriter(Vec::new());
4625                 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4626                 node_0_monitors_serialized.push(writer.0);
4627         }
4628
4629         logger = test_utils::TestLogger::new();
4630         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4631         persister = test_utils::TestPersister::new();
4632         let keys_manager = &chanmon_cfgs[0].keys_manager;
4633         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4634         nodes[0].chain_monitor = &new_chain_monitor;
4635
4636
4637         let mut node_0_stale_monitors = Vec::new();
4638         for serialized in node_0_stale_monitors_serialized.iter() {
4639                 let mut read = &serialized[..];
4640                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4641                 assert!(read.is_empty());
4642                 node_0_stale_monitors.push(monitor);
4643         }
4644
4645         let mut node_0_monitors = Vec::new();
4646         for serialized in node_0_monitors_serialized.iter() {
4647                 let mut read = &serialized[..];
4648                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4649                 assert!(read.is_empty());
4650                 node_0_monitors.push(monitor);
4651         }
4652
4653         let mut nodes_0_read = &nodes_0_serialized[..];
4654         if let Err(msgs::DecodeError::InvalidValue) =
4655                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4656                 default_config: UserConfig::default(),
4657                 keys_manager,
4658                 fee_estimator: &fee_estimator,
4659                 chain_monitor: nodes[0].chain_monitor,
4660                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4661                 logger: &logger,
4662                 channel_monitors: node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4663         }) { } else {
4664                 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4665         };
4666
4667         let mut nodes_0_read = &nodes_0_serialized[..];
4668         let (_, nodes_0_deserialized_tmp) =
4669                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4670                 default_config: UserConfig::default(),
4671                 keys_manager,
4672                 fee_estimator: &fee_estimator,
4673                 chain_monitor: nodes[0].chain_monitor,
4674                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4675                 logger: &logger,
4676                 channel_monitors: node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4677         }).unwrap();
4678         nodes_0_deserialized = nodes_0_deserialized_tmp;
4679         assert!(nodes_0_read.is_empty());
4680
4681         { // Channel close should result in a commitment tx
4682                 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4683                 assert_eq!(txn.len(), 1);
4684                 check_spends!(txn[0], funding_tx);
4685                 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4686         }
4687
4688         for monitor in node_0_monitors.drain(..) {
4689                 assert!(nodes[0].chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor).is_ok());
4690                 check_added_monitors!(nodes[0], 1);
4691         }
4692         nodes[0].node = &nodes_0_deserialized;
4693         check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
4694
4695         // nodes[1] and nodes[2] have no lost state with nodes[0]...
4696         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4697         reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4698         //... and we can even still claim the payment!
4699         claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage);
4700
4701         nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4702         let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4703         nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4704         nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4705         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4706         assert_eq!(msg_events.len(), 1);
4707         if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
4708                 match action {
4709                         &ErrorAction::SendErrorMessage { ref msg } => {
4710                                 assert_eq!(msg.channel_id, channel_id);
4711                         },
4712                         _ => panic!("Unexpected event!"),
4713                 }
4714         }
4715 }
4716
4717 macro_rules! check_spendable_outputs {
4718         ($node: expr, $keysinterface: expr) => {
4719                 {
4720                         let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4721                         let mut txn = Vec::new();
4722                         let mut all_outputs = Vec::new();
4723                         let secp_ctx = Secp256k1::new();
4724                         for event in events.drain(..) {
4725                                 match event {
4726                                         Event::SpendableOutputs { mut outputs } => {
4727                                                 for outp in outputs.drain(..) {
4728                                                         txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4729                                                         all_outputs.push(outp);
4730                                                 }
4731                                         },
4732                                         _ => panic!("Unexpected event"),
4733                                 };
4734                         }
4735                         if all_outputs.len() > 1 {
4736                                 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) {
4737                                         txn.push(tx);
4738                                 }
4739                         }
4740                         txn
4741                 }
4742         }
4743 }
4744
4745 #[test]
4746 fn test_claim_sizeable_push_msat() {
4747         // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4748         let chanmon_cfgs = create_chanmon_cfgs(2);
4749         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4750         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4751         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4752
4753         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000, InitFeatures::known(), InitFeatures::known());
4754         nodes[1].node.force_close_channel(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
4755         check_closed_broadcast!(nodes[1], true);
4756         check_added_monitors!(nodes[1], 1);
4757         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4758         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4759         assert_eq!(node_txn.len(), 1);
4760         check_spends!(node_txn[0], chan.3);
4761         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
4762
4763         mine_transaction(&nodes[1], &node_txn[0]);
4764         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4765
4766         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4767         assert_eq!(spend_txn.len(), 1);
4768         assert_eq!(spend_txn[0].input.len(), 1);
4769         check_spends!(spend_txn[0], node_txn[0]);
4770         assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
4771 }
4772
4773 #[test]
4774 fn test_claim_on_remote_sizeable_push_msat() {
4775         // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4776         // to_remote output is encumbered by a P2WPKH
4777         let chanmon_cfgs = create_chanmon_cfgs(2);
4778         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4779         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4780         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4781
4782         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000, InitFeatures::known(), InitFeatures::known());
4783         nodes[0].node.force_close_channel(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
4784         check_closed_broadcast!(nodes[0], true);
4785         check_added_monitors!(nodes[0], 1);
4786         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4787
4788         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4789         assert_eq!(node_txn.len(), 1);
4790         check_spends!(node_txn[0], chan.3);
4791         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
4792
4793         mine_transaction(&nodes[1], &node_txn[0]);
4794         check_closed_broadcast!(nodes[1], true);
4795         check_added_monitors!(nodes[1], 1);
4796         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4797         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4798
4799         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4800         assert_eq!(spend_txn.len(), 1);
4801         check_spends!(spend_txn[0], node_txn[0]);
4802 }
4803
4804 #[test]
4805 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4806         // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4807         // to_remote output is encumbered by a P2WPKH
4808
4809         let chanmon_cfgs = create_chanmon_cfgs(2);
4810         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4811         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4812         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4813
4814         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::known(), InitFeatures::known());
4815         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4816         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4817         assert_eq!(revoked_local_txn[0].input.len(), 1);
4818         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4819
4820         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4821         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4822         check_closed_broadcast!(nodes[1], true);
4823         check_added_monitors!(nodes[1], 1);
4824         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4825
4826         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4827         mine_transaction(&nodes[1], &node_txn[0]);
4828         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4829
4830         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4831         assert_eq!(spend_txn.len(), 3);
4832         check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4833         check_spends!(spend_txn[1], node_txn[0]);
4834         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4835 }
4836
4837 #[test]
4838 fn test_static_spendable_outputs_preimage_tx() {
4839         let chanmon_cfgs = create_chanmon_cfgs(2);
4840         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4841         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4842         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4843
4844         // Create some initial channels
4845         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4846
4847         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4848
4849         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4850         assert_eq!(commitment_tx[0].input.len(), 1);
4851         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4852
4853         // Settle A's commitment tx on B's chain
4854         assert!(nodes[1].node.claim_funds(payment_preimage));
4855         check_added_monitors!(nodes[1], 1);
4856         mine_transaction(&nodes[1], &commitment_tx[0]);
4857         check_added_monitors!(nodes[1], 1);
4858         let events = nodes[1].node.get_and_clear_pending_msg_events();
4859         match events[0] {
4860                 MessageSendEvent::UpdateHTLCs { .. } => {},
4861                 _ => panic!("Unexpected event"),
4862         }
4863         match events[1] {
4864                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4865                 _ => panic!("Unexepected event"),
4866         }
4867
4868         // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4869         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4870         assert_eq!(node_txn.len(), 3);
4871         check_spends!(node_txn[0], commitment_tx[0]);
4872         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4873         check_spends!(node_txn[1], chan_1.3);
4874         check_spends!(node_txn[2], node_txn[1]);
4875
4876         mine_transaction(&nodes[1], &node_txn[0]);
4877         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4878         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4879
4880         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4881         assert_eq!(spend_txn.len(), 1);
4882         check_spends!(spend_txn[0], node_txn[0]);
4883 }
4884
4885 #[test]
4886 fn test_static_spendable_outputs_timeout_tx() {
4887         let chanmon_cfgs = create_chanmon_cfgs(2);
4888         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4889         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4890         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4891
4892         // Create some initial channels
4893         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4894
4895         // Rebalance the network a bit by relaying one payment through all the channels ...
4896         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4897
4898         let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4899
4900         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4901         assert_eq!(commitment_tx[0].input.len(), 1);
4902         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4903
4904         // Settle A's commitment tx on B' chain
4905         mine_transaction(&nodes[1], &commitment_tx[0]);
4906         check_added_monitors!(nodes[1], 1);
4907         let events = nodes[1].node.get_and_clear_pending_msg_events();
4908         match events[0] {
4909                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4910                 _ => panic!("Unexpected event"),
4911         }
4912         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4913
4914         // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4915         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4916         assert_eq!(node_txn.len(), 2); // ChannelManager : 1 local commitent tx, ChannelMonitor: timeout tx
4917         check_spends!(node_txn[0], chan_1.3.clone());
4918         check_spends!(node_txn[1],  commitment_tx[0].clone());
4919         assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4920
4921         mine_transaction(&nodes[1], &node_txn[1]);
4922         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4923         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4924         expect_payment_failed!(nodes[1], our_payment_hash, true);
4925
4926         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4927         assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4928         check_spends!(spend_txn[0], commitment_tx[0]);
4929         check_spends!(spend_txn[1], node_txn[1]);
4930         check_spends!(spend_txn[2], node_txn[1], commitment_tx[0]); // All outputs
4931 }
4932
4933 #[test]
4934 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4935         let chanmon_cfgs = create_chanmon_cfgs(2);
4936         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4937         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4938         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4939
4940         // Create some initial channels
4941         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4942
4943         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4944         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4945         assert_eq!(revoked_local_txn[0].input.len(), 1);
4946         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4947
4948         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4949
4950         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4951         check_closed_broadcast!(nodes[1], true);
4952         check_added_monitors!(nodes[1], 1);
4953         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4954
4955         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4956         assert_eq!(node_txn.len(), 2);
4957         assert_eq!(node_txn[0].input.len(), 2);
4958         check_spends!(node_txn[0], revoked_local_txn[0]);
4959
4960         mine_transaction(&nodes[1], &node_txn[0]);
4961         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4962
4963         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4964         assert_eq!(spend_txn.len(), 1);
4965         check_spends!(spend_txn[0], node_txn[0]);
4966 }
4967
4968 #[test]
4969 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4970         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4971         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4972         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4973         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4974         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4975
4976         // Create some initial channels
4977         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4978
4979         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4980         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4981         assert_eq!(revoked_local_txn[0].input.len(), 1);
4982         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4983
4984         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4985
4986         // A will generate HTLC-Timeout from revoked commitment tx
4987         mine_transaction(&nodes[0], &revoked_local_txn[0]);
4988         check_closed_broadcast!(nodes[0], true);
4989         check_added_monitors!(nodes[0], 1);
4990         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4991         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4992
4993         let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4994         assert_eq!(revoked_htlc_txn.len(), 2);
4995         check_spends!(revoked_htlc_txn[0], chan_1.3);
4996         assert_eq!(revoked_htlc_txn[1].input.len(), 1);
4997         assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4998         check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
4999         assert_ne!(revoked_htlc_txn[1].lock_time, 0); // HTLC-Timeout
5000
5001         // B will generate justice tx from A's revoked commitment/HTLC tx
5002         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5003         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[1].clone()] });
5004         check_closed_broadcast!(nodes[1], true);
5005         check_added_monitors!(nodes[1], 1);
5006         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5007
5008         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5009         assert_eq!(node_txn.len(), 3); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs, ChannelManager: local commitment tx
5010         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5011         // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
5012         // transactions next...
5013         assert_eq!(node_txn[0].input.len(), 3);
5014         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[1]);
5015
5016         assert_eq!(node_txn[1].input.len(), 2);
5017         check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[1]);
5018         if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[1].txid() {
5019                 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
5020         } else {
5021                 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[1].txid());
5022                 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[1].input[0].previous_output);
5023         }
5024
5025         assert_eq!(node_txn[2].input.len(), 1);
5026         check_spends!(node_txn[2], chan_1.3);
5027
5028         mine_transaction(&nodes[1], &node_txn[1]);
5029         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5030
5031         // Check B's ChannelMonitor was able to generate the right spendable output descriptor
5032         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5033         assert_eq!(spend_txn.len(), 1);
5034         assert_eq!(spend_txn[0].input.len(), 1);
5035         check_spends!(spend_txn[0], node_txn[1]);
5036 }
5037
5038 #[test]
5039 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
5040         let mut chanmon_cfgs = create_chanmon_cfgs(2);
5041         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
5042         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5043         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5044         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5045
5046         // Create some initial channels
5047         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5048
5049         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5050         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5051         assert_eq!(revoked_local_txn[0].input.len(), 1);
5052         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5053
5054         // The to-be-revoked commitment tx should have one HTLC and one to_remote output
5055         assert_eq!(revoked_local_txn[0].output.len(), 2);
5056
5057         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
5058
5059         // B will generate HTLC-Success from revoked commitment tx
5060         mine_transaction(&nodes[1], &revoked_local_txn[0]);
5061         check_closed_broadcast!(nodes[1], true);
5062         check_added_monitors!(nodes[1], 1);
5063         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5064         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5065
5066         assert_eq!(revoked_htlc_txn.len(), 2);
5067         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
5068         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5069         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
5070
5071         // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
5072         let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
5073         assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
5074
5075         // A will generate justice tx from B's revoked commitment/HTLC tx
5076         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5077         connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
5078         check_closed_broadcast!(nodes[0], true);
5079         check_added_monitors!(nodes[0], 1);
5080         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5081
5082         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5083         assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
5084
5085         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5086         // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
5087         // transactions next...
5088         assert_eq!(node_txn[0].input.len(), 2);
5089         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
5090         if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
5091                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5092         } else {
5093                 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
5094                 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5095         }
5096
5097         assert_eq!(node_txn[1].input.len(), 1);
5098         check_spends!(node_txn[1], revoked_htlc_txn[0]);
5099
5100         check_spends!(node_txn[2], chan_1.3);
5101
5102         mine_transaction(&nodes[0], &node_txn[1]);
5103         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5104
5105         // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
5106         // didn't try to generate any new transactions.
5107
5108         // Check A's ChannelMonitor was able to generate the right spendable output descriptor
5109         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5110         assert_eq!(spend_txn.len(), 3);
5111         assert_eq!(spend_txn[0].input.len(), 1);
5112         check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
5113         assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5114         check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
5115         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
5116 }
5117
5118 #[test]
5119 fn test_onchain_to_onchain_claim() {
5120         // Test that in case of channel closure, we detect the state of output and claim HTLC
5121         // on downstream peer's remote commitment tx.
5122         // First, have C claim an HTLC against its own latest commitment transaction.
5123         // Then, broadcast these to B, which should update the monitor downstream on the A<->B
5124         // channel.
5125         // Finally, check that B will claim the HTLC output if A's latest commitment transaction
5126         // gets broadcast.
5127
5128         let chanmon_cfgs = create_chanmon_cfgs(3);
5129         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5130         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5131         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5132
5133         // Create some initial channels
5134         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5135         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5136
5137         // Ensure all nodes are at the same height
5138         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5139         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5140         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5141         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5142
5143         // Rebalance the network a bit by relaying one payment through all the channels ...
5144         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5145         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5146
5147         let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
5148         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
5149         check_spends!(commitment_tx[0], chan_2.3);
5150         nodes[2].node.claim_funds(payment_preimage);
5151         check_added_monitors!(nodes[2], 1);
5152         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5153         assert!(updates.update_add_htlcs.is_empty());
5154         assert!(updates.update_fail_htlcs.is_empty());
5155         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5156         assert!(updates.update_fail_malformed_htlcs.is_empty());
5157
5158         mine_transaction(&nodes[2], &commitment_tx[0]);
5159         check_closed_broadcast!(nodes[2], true);
5160         check_added_monitors!(nodes[2], 1);
5161         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5162
5163         let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
5164         assert_eq!(c_txn.len(), 3);
5165         assert_eq!(c_txn[0], c_txn[2]);
5166         assert_eq!(commitment_tx[0], c_txn[1]);
5167         check_spends!(c_txn[1], chan_2.3);
5168         check_spends!(c_txn[2], c_txn[1]);
5169         assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
5170         assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5171         assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5172         assert_eq!(c_txn[0].lock_time, 0); // Success tx
5173
5174         // 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
5175         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
5176         connect_block(&nodes[1], &Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]});
5177         check_added_monitors!(nodes[1], 1);
5178         let events = nodes[1].node.get_and_clear_pending_events();
5179         assert_eq!(events.len(), 2);
5180         match events[0] {
5181                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5182                 _ => panic!("Unexpected event"),
5183         }
5184         match events[1] {
5185                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
5186                         assert_eq!(fee_earned_msat, Some(1000));
5187                         assert_eq!(prev_channel_id, Some(chan_1.2));
5188                         assert_eq!(claim_from_onchain_tx, true);
5189                         assert_eq!(next_channel_id, Some(chan_2.2));
5190                 },
5191                 _ => panic!("Unexpected event"),
5192         }
5193         {
5194                 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5195                 // ChannelMonitor: claim tx
5196                 assert_eq!(b_txn.len(), 1);
5197                 check_spends!(b_txn[0], chan_2.3); // B local commitment tx, issued by ChannelManager
5198                 b_txn.clear();
5199         }
5200         check_added_monitors!(nodes[1], 1);
5201         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5202         assert_eq!(msg_events.len(), 3);
5203         match msg_events[0] {
5204                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5205                 _ => panic!("Unexpected event"),
5206         }
5207         match msg_events[1] {
5208                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
5209                 _ => panic!("Unexpected event"),
5210         }
5211         match msg_events[2] {
5212                 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, .. } } => {
5213                         assert!(update_add_htlcs.is_empty());
5214                         assert!(update_fail_htlcs.is_empty());
5215                         assert_eq!(update_fulfill_htlcs.len(), 1);
5216                         assert!(update_fail_malformed_htlcs.is_empty());
5217                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5218                 },
5219                 _ => panic!("Unexpected event"),
5220         };
5221         // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
5222         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5223         mine_transaction(&nodes[1], &commitment_tx[0]);
5224         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5225         let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5226         // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
5227         assert_eq!(b_txn.len(), 3);
5228         check_spends!(b_txn[1], chan_1.3);
5229         check_spends!(b_txn[2], b_txn[1]);
5230         check_spends!(b_txn[0], commitment_tx[0]);
5231         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5232         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5233         assert_eq!(b_txn[0].lock_time, 0); // Success tx
5234
5235         check_closed_broadcast!(nodes[1], true);
5236         check_added_monitors!(nodes[1], 1);
5237 }
5238
5239 #[test]
5240 fn test_duplicate_payment_hash_one_failure_one_success() {
5241         // Topology : A --> B --> C --> D
5242         // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5243         // Note that because C will refuse to generate two payment secrets for the same payment hash,
5244         // we forward one of the payments onwards to D.
5245         let chanmon_cfgs = create_chanmon_cfgs(4);
5246         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
5247         // When this test was written, the default base fee floated based on the HTLC count.
5248         // It is now fixed, so we simply set the fee to the expected value here.
5249         let mut config = test_default_channel_config();
5250         config.channel_options.forwarding_fee_base_msat = 196;
5251         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
5252                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5253         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
5254
5255         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5256         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5257         create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5258
5259         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5260         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5261         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5262         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5263         connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
5264
5265         let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
5266
5267         let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200).unwrap();
5268         // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
5269         // script push size limit so that the below script length checks match
5270         // ACCEPTED_HTLC_SCRIPT_WEIGHT.
5271         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id())
5272                 .with_features(InvoiceFeatures::known());
5273         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 900000, TEST_FINAL_CLTV - 40);
5274         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 900000, duplicate_payment_hash, payment_secret);
5275
5276         let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5277         assert_eq!(commitment_txn[0].input.len(), 1);
5278         check_spends!(commitment_txn[0], chan_2.3);
5279
5280         mine_transaction(&nodes[1], &commitment_txn[0]);
5281         check_closed_broadcast!(nodes[1], true);
5282         check_added_monitors!(nodes[1], 1);
5283         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5284         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
5285
5286         let htlc_timeout_tx;
5287         { // Extract one of the two HTLC-Timeout transaction
5288                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5289                 // ChannelMonitor: timeout tx * 3, ChannelManager: local commitment tx
5290                 assert_eq!(node_txn.len(), 4);
5291                 check_spends!(node_txn[0], chan_2.3);
5292
5293                 check_spends!(node_txn[1], commitment_txn[0]);
5294                 assert_eq!(node_txn[1].input.len(), 1);
5295                 check_spends!(node_txn[2], commitment_txn[0]);
5296                 assert_eq!(node_txn[2].input.len(), 1);
5297                 assert_eq!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
5298                 check_spends!(node_txn[3], commitment_txn[0]);
5299                 assert_ne!(node_txn[1].input[0].previous_output, node_txn[3].input[0].previous_output);
5300
5301                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5302                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5303                 assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5304                 htlc_timeout_tx = node_txn[1].clone();
5305         }
5306
5307         nodes[2].node.claim_funds(our_payment_preimage);
5308         mine_transaction(&nodes[2], &commitment_txn[0]);
5309         check_added_monitors!(nodes[2], 2);
5310         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5311         let events = nodes[2].node.get_and_clear_pending_msg_events();
5312         match events[0] {
5313                 MessageSendEvent::UpdateHTLCs { .. } => {},
5314                 _ => panic!("Unexpected event"),
5315         }
5316         match events[1] {
5317                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5318                 _ => panic!("Unexepected event"),
5319         }
5320         let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5321         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)
5322         check_spends!(htlc_success_txn[0], commitment_txn[0]);
5323         check_spends!(htlc_success_txn[1], commitment_txn[0]);
5324         assert_eq!(htlc_success_txn[0].input.len(), 1);
5325         assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5326         assert_eq!(htlc_success_txn[1].input.len(), 1);
5327         assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5328         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
5329         assert_eq!(htlc_success_txn[2], commitment_txn[0]);
5330         assert_eq!(htlc_success_txn[3], htlc_success_txn[0]);
5331         assert_eq!(htlc_success_txn[4], htlc_success_txn[1]);
5332         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
5333
5334         mine_transaction(&nodes[1], &htlc_timeout_tx);
5335         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5336         expect_pending_htlcs_forwardable!(nodes[1]);
5337         let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5338         assert!(htlc_updates.update_add_htlcs.is_empty());
5339         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5340         let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
5341         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5342         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5343         check_added_monitors!(nodes[1], 1);
5344
5345         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5346         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5347         {
5348                 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5349         }
5350         expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
5351
5352         // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5353         // Note that the fee paid is effectively double as the HTLC value (including the nodes[1] fee
5354         // and nodes[2] fee) is rounded down and then claimed in full.
5355         mine_transaction(&nodes[1], &htlc_success_txn[0]);
5356         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196*2), true, true);
5357         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5358         assert!(updates.update_add_htlcs.is_empty());
5359         assert!(updates.update_fail_htlcs.is_empty());
5360         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5361         assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
5362         assert!(updates.update_fail_malformed_htlcs.is_empty());
5363         check_added_monitors!(nodes[1], 1);
5364
5365         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5366         commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5367
5368         let events = nodes[0].node.get_and_clear_pending_events();
5369         match events[0] {
5370                 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
5371                         assert_eq!(*payment_preimage, our_payment_preimage);
5372                         assert_eq!(*payment_hash, duplicate_payment_hash);
5373                 }
5374                 _ => panic!("Unexpected event"),
5375         }
5376 }
5377
5378 #[test]
5379 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5380         let chanmon_cfgs = create_chanmon_cfgs(2);
5381         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5382         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5383         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5384
5385         // Create some initial channels
5386         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5387
5388         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
5389         let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5390         assert_eq!(local_txn.len(), 1);
5391         assert_eq!(local_txn[0].input.len(), 1);
5392         check_spends!(local_txn[0], chan_1.3);
5393
5394         // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5395         nodes[1].node.claim_funds(payment_preimage);
5396         check_added_monitors!(nodes[1], 1);
5397         mine_transaction(&nodes[1], &local_txn[0]);
5398         check_added_monitors!(nodes[1], 1);
5399         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5400         let events = nodes[1].node.get_and_clear_pending_msg_events();
5401         match events[0] {
5402                 MessageSendEvent::UpdateHTLCs { .. } => {},
5403                 _ => panic!("Unexpected event"),
5404         }
5405         match events[1] {
5406                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5407                 _ => panic!("Unexepected event"),
5408         }
5409         let node_tx = {
5410                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5411                 assert_eq!(node_txn.len(), 3);
5412                 assert_eq!(node_txn[0], node_txn[2]);
5413                 assert_eq!(node_txn[1], local_txn[0]);
5414                 assert_eq!(node_txn[0].input.len(), 1);
5415                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5416                 check_spends!(node_txn[0], local_txn[0]);
5417                 node_txn[0].clone()
5418         };
5419
5420         mine_transaction(&nodes[1], &node_tx);
5421         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
5422
5423         // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5424         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5425         assert_eq!(spend_txn.len(), 1);
5426         assert_eq!(spend_txn[0].input.len(), 1);
5427         check_spends!(spend_txn[0], node_tx);
5428         assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5429 }
5430
5431 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5432         // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5433         // unrevoked commitment transaction.
5434         // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5435         // a remote RAA before they could be failed backwards (and combinations thereof).
5436         // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5437         // use the same payment hashes.
5438         // Thus, we use a six-node network:
5439         //
5440         // A \         / E
5441         //    - C - D -
5442         // B /         \ F
5443         // And test where C fails back to A/B when D announces its latest commitment transaction
5444         let chanmon_cfgs = create_chanmon_cfgs(6);
5445         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5446         // When this test was written, the default base fee floated based on the HTLC count.
5447         // It is now fixed, so we simply set the fee to the expected value here.
5448         let mut config = test_default_channel_config();
5449         config.channel_options.forwarding_fee_base_msat = 196;
5450         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
5451                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5452         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5453
5454         create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5455         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5456         let chan = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5457         create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
5458         create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
5459
5460         // Rebalance and check output sanity...
5461         send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
5462         send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
5463         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 2);
5464
5465         let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
5466         // 0th HTLC:
5467         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
5468         // 1st HTLC:
5469         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
5470         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5471         // 2nd HTLC:
5472         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
5473         // 3rd HTLC:
5474         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
5475         // 4th HTLC:
5476         let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5477         // 5th HTLC:
5478         let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5479         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5480         // 6th HTLC:
5481         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());
5482         // 7th HTLC:
5483         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());
5484
5485         // 8th HTLC:
5486         let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5487         // 9th HTLC:
5488         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5489         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
5490
5491         // 10th HTLC:
5492         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
5493         // 11th HTLC:
5494         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5495         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());
5496
5497         // Double-check that six of the new HTLC were added
5498         // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5499         // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5500         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2).len(), 1);
5501         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 8);
5502
5503         // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5504         // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5505         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_1));
5506         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_3));
5507         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_5));
5508         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_6));
5509         check_added_monitors!(nodes[4], 0);
5510         expect_pending_htlcs_forwardable!(nodes[4]);
5511         check_added_monitors!(nodes[4], 1);
5512
5513         let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5514         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5515         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5516         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5517         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5518         commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5519
5520         // Fail 3rd below-dust and 7th above-dust HTLCs
5521         assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_2));
5522         assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_4));
5523         check_added_monitors!(nodes[5], 0);
5524         expect_pending_htlcs_forwardable!(nodes[5]);
5525         check_added_monitors!(nodes[5], 1);
5526
5527         let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5528         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5529         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5530         commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5531
5532         let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5533
5534         expect_pending_htlcs_forwardable!(nodes[3]);
5535         check_added_monitors!(nodes[3], 1);
5536         let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5537         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5538         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5539         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5540         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5541         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5542         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5543         if deliver_last_raa {
5544                 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5545         } else {
5546                 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5547         }
5548
5549         // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5550         // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5551         // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5552         // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5553         //
5554         // We now broadcast the latest commitment transaction, which *should* result in failures for
5555         // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5556         // the non-broadcast above-dust HTLCs.
5557         //
5558         // Alternatively, we may broadcast the previous commitment transaction, which should only
5559         // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5560         let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5561
5562         if announce_latest {
5563                 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5564         } else {
5565                 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5566         }
5567         let events = nodes[2].node.get_and_clear_pending_events();
5568         let close_event = if deliver_last_raa {
5569                 assert_eq!(events.len(), 2);
5570                 events[1].clone()
5571         } else {
5572                 assert_eq!(events.len(), 1);
5573                 events[0].clone()
5574         };
5575         match close_event {
5576                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5577                 _ => panic!("Unexpected event"),
5578         }
5579
5580         connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5581         check_closed_broadcast!(nodes[2], true);
5582         if deliver_last_raa {
5583                 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5584         } else {
5585                 expect_pending_htlcs_forwardable!(nodes[2]);
5586         }
5587         check_added_monitors!(nodes[2], 3);
5588
5589         let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5590         assert_eq!(cs_msgs.len(), 2);
5591         let mut a_done = false;
5592         for msg in cs_msgs {
5593                 match msg {
5594                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5595                                 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5596                                 // should be failed-backwards here.
5597                                 let target = if *node_id == nodes[0].node.get_our_node_id() {
5598                                         // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5599                                         for htlc in &updates.update_fail_htlcs {
5600                                                 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 });
5601                                         }
5602                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5603                                         assert!(!a_done);
5604                                         a_done = true;
5605                                         &nodes[0]
5606                                 } else {
5607                                         // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5608                                         for htlc in &updates.update_fail_htlcs {
5609                                                 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5610                                         }
5611                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5612                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5613                                         &nodes[1]
5614                                 };
5615                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5616                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5617                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5618                                 if announce_latest {
5619                                         target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5620                                         if *node_id == nodes[0].node.get_our_node_id() {
5621                                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5622                                         }
5623                                 }
5624                                 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5625                         },
5626                         _ => panic!("Unexpected event"),
5627                 }
5628         }
5629
5630         let as_events = nodes[0].node.get_and_clear_pending_events();
5631         assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5632         let mut as_failds = HashSet::new();
5633         let mut as_updates = 0;
5634         for event in as_events.iter() {
5635                 if let &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5636                         assert!(as_failds.insert(*payment_hash));
5637                         if *payment_hash != payment_hash_2 {
5638                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5639                         } else {
5640                                 assert!(!rejected_by_dest);
5641                         }
5642                         if network_update.is_some() {
5643                                 as_updates += 1;
5644                         }
5645                 } else { panic!("Unexpected event"); }
5646         }
5647         assert!(as_failds.contains(&payment_hash_1));
5648         assert!(as_failds.contains(&payment_hash_2));
5649         if announce_latest {
5650                 assert!(as_failds.contains(&payment_hash_3));
5651                 assert!(as_failds.contains(&payment_hash_5));
5652         }
5653         assert!(as_failds.contains(&payment_hash_6));
5654
5655         let bs_events = nodes[1].node.get_and_clear_pending_events();
5656         assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5657         let mut bs_failds = HashSet::new();
5658         let mut bs_updates = 0;
5659         for event in bs_events.iter() {
5660                 if let &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5661                         assert!(bs_failds.insert(*payment_hash));
5662                         if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5663                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5664                         } else {
5665                                 assert!(!rejected_by_dest);
5666                         }
5667                         if network_update.is_some() {
5668                                 bs_updates += 1;
5669                         }
5670                 } else { panic!("Unexpected event"); }
5671         }
5672         assert!(bs_failds.contains(&payment_hash_1));
5673         assert!(bs_failds.contains(&payment_hash_2));
5674         if announce_latest {
5675                 assert!(bs_failds.contains(&payment_hash_4));
5676         }
5677         assert!(bs_failds.contains(&payment_hash_5));
5678
5679         // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5680         // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5681         // unknown-preimage-etc, B should have gotten 2. Thus, in the
5682         // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5683         assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5684         assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5685 }
5686
5687 #[test]
5688 fn test_fail_backwards_latest_remote_announce_a() {
5689         do_test_fail_backwards_unrevoked_remote_announce(false, true);
5690 }
5691
5692 #[test]
5693 fn test_fail_backwards_latest_remote_announce_b() {
5694         do_test_fail_backwards_unrevoked_remote_announce(true, true);
5695 }
5696
5697 #[test]
5698 fn test_fail_backwards_previous_remote_announce() {
5699         do_test_fail_backwards_unrevoked_remote_announce(false, false);
5700         // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5701         // tested for in test_commitment_revoked_fail_backward_exhaustive()
5702 }
5703
5704 #[test]
5705 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5706         let chanmon_cfgs = create_chanmon_cfgs(2);
5707         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5708         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5709         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5710
5711         // Create some initial channels
5712         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5713
5714         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5715         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5716         assert_eq!(local_txn[0].input.len(), 1);
5717         check_spends!(local_txn[0], chan_1.3);
5718
5719         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5720         mine_transaction(&nodes[0], &local_txn[0]);
5721         check_closed_broadcast!(nodes[0], true);
5722         check_added_monitors!(nodes[0], 1);
5723         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5724         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5725
5726         let htlc_timeout = {
5727                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5728                 assert_eq!(node_txn.len(), 2);
5729                 check_spends!(node_txn[0], chan_1.3);
5730                 assert_eq!(node_txn[1].input.len(), 1);
5731                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5732                 check_spends!(node_txn[1], local_txn[0]);
5733                 node_txn[1].clone()
5734         };
5735
5736         mine_transaction(&nodes[0], &htlc_timeout);
5737         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5738         expect_payment_failed!(nodes[0], our_payment_hash, true);
5739
5740         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5741         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5742         assert_eq!(spend_txn.len(), 3);
5743         check_spends!(spend_txn[0], local_txn[0]);
5744         assert_eq!(spend_txn[1].input.len(), 1);
5745         check_spends!(spend_txn[1], htlc_timeout);
5746         assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5747         assert_eq!(spend_txn[2].input.len(), 2);
5748         check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5749         assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5750                 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5751 }
5752
5753 #[test]
5754 fn test_key_derivation_params() {
5755         // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5756         // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5757         // let us re-derive the channel key set to then derive a delayed_payment_key.
5758
5759         let chanmon_cfgs = create_chanmon_cfgs(3);
5760
5761         // We manually create the node configuration to backup the seed.
5762         let seed = [42; 32];
5763         let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5764         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);
5765         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() };
5766         let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5767         node_cfgs.remove(0);
5768         node_cfgs.insert(0, node);
5769
5770         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5771         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5772
5773         // Create some initial channels
5774         // Create a dummy channel to advance index by one and thus test re-derivation correctness
5775         // for node 0
5776         let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5777         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5778         assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5779
5780         // Ensure all nodes are at the same height
5781         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5782         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5783         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5784         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5785
5786         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5787         let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5788         let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5789         assert_eq!(local_txn_1[0].input.len(), 1);
5790         check_spends!(local_txn_1[0], chan_1.3);
5791
5792         // We check funding pubkey are unique
5793         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]));
5794         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]));
5795         if from_0_funding_key_0 == from_1_funding_key_0
5796             || from_0_funding_key_0 == from_1_funding_key_1
5797             || from_0_funding_key_1 == from_1_funding_key_0
5798             || from_0_funding_key_1 == from_1_funding_key_1 {
5799                 panic!("Funding pubkeys aren't unique");
5800         }
5801
5802         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5803         mine_transaction(&nodes[0], &local_txn_1[0]);
5804         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5805         check_closed_broadcast!(nodes[0], true);
5806         check_added_monitors!(nodes[0], 1);
5807         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5808
5809         let htlc_timeout = {
5810                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5811                 assert_eq!(node_txn[1].input.len(), 1);
5812                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5813                 check_spends!(node_txn[1], local_txn_1[0]);
5814                 node_txn[1].clone()
5815         };
5816
5817         mine_transaction(&nodes[0], &htlc_timeout);
5818         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5819         expect_payment_failed!(nodes[0], our_payment_hash, true);
5820
5821         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5822         let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5823         let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5824         assert_eq!(spend_txn.len(), 3);
5825         check_spends!(spend_txn[0], local_txn_1[0]);
5826         assert_eq!(spend_txn[1].input.len(), 1);
5827         check_spends!(spend_txn[1], htlc_timeout);
5828         assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5829         assert_eq!(spend_txn[2].input.len(), 2);
5830         check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5831         assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5832                 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5833 }
5834
5835 #[test]
5836 fn test_static_output_closing_tx() {
5837         let chanmon_cfgs = create_chanmon_cfgs(2);
5838         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5839         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5840         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5841
5842         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5843
5844         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5845         let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5846
5847         mine_transaction(&nodes[0], &closing_tx);
5848         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5849         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5850
5851         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5852         assert_eq!(spend_txn.len(), 1);
5853         check_spends!(spend_txn[0], closing_tx);
5854
5855         mine_transaction(&nodes[1], &closing_tx);
5856         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5857         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5858
5859         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5860         assert_eq!(spend_txn.len(), 1);
5861         check_spends!(spend_txn[0], closing_tx);
5862 }
5863
5864 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5865         let chanmon_cfgs = create_chanmon_cfgs(2);
5866         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5867         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5868         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5869         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5870
5871         let (payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3000000 });
5872
5873         // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5874         // present in B's local commitment transaction, but none of A's commitment transactions.
5875         assert!(nodes[1].node.claim_funds(payment_preimage));
5876         check_added_monitors!(nodes[1], 1);
5877
5878         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5879         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5880         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
5881
5882         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5883         check_added_monitors!(nodes[0], 1);
5884         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5885         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5886         check_added_monitors!(nodes[1], 1);
5887
5888         let starting_block = nodes[1].best_block_info();
5889         let mut block = Block {
5890                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5891                 txdata: vec![],
5892         };
5893         for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5894                 connect_block(&nodes[1], &block);
5895                 block.header.prev_blockhash = block.block_hash();
5896         }
5897         test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5898         check_closed_broadcast!(nodes[1], true);
5899         check_added_monitors!(nodes[1], 1);
5900         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5901 }
5902
5903 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5904         let chanmon_cfgs = create_chanmon_cfgs(2);
5905         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5906         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5907         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5908         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5909
5910         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5911         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
5912         check_added_monitors!(nodes[0], 1);
5913
5914         let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5915
5916         // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5917         // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5918         // to "time out" the HTLC.
5919
5920         let starting_block = nodes[1].best_block_info();
5921         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5922
5923         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5924                 connect_block(&nodes[0], &Block { header, txdata: Vec::new()});
5925                 header.prev_blockhash = header.block_hash();
5926         }
5927         test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5928         check_closed_broadcast!(nodes[0], true);
5929         check_added_monitors!(nodes[0], 1);
5930         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5931 }
5932
5933 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5934         let chanmon_cfgs = create_chanmon_cfgs(3);
5935         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5936         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5937         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5938         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5939
5940         // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5941         // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5942         // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5943         // actually revoked.
5944         let htlc_value = if use_dust { 50000 } else { 3000000 };
5945         let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5946         assert!(nodes[1].node.fail_htlc_backwards(&our_payment_hash));
5947         expect_pending_htlcs_forwardable!(nodes[1]);
5948         check_added_monitors!(nodes[1], 1);
5949
5950         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5951         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5952         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5953         check_added_monitors!(nodes[0], 1);
5954         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5955         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5956         check_added_monitors!(nodes[1], 1);
5957         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5958         check_added_monitors!(nodes[1], 1);
5959         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5960
5961         if check_revoke_no_close {
5962                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5963                 check_added_monitors!(nodes[0], 1);
5964         }
5965
5966         let starting_block = nodes[1].best_block_info();
5967         let mut block = Block {
5968                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5969                 txdata: vec![],
5970         };
5971         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5972                 connect_block(&nodes[0], &block);
5973                 block.header.prev_blockhash = block.block_hash();
5974         }
5975         if !check_revoke_no_close {
5976                 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5977                 check_closed_broadcast!(nodes[0], true);
5978                 check_added_monitors!(nodes[0], 1);
5979                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5980         } else {
5981                 let events = nodes[0].node.get_and_clear_pending_events();
5982                 assert_eq!(events.len(), 2);
5983                 if let Event::PaymentPathFailed { ref payment_hash, .. } = events[0] {
5984                         assert_eq!(*payment_hash, our_payment_hash);
5985                 } else { panic!("Unexpected event"); }
5986                 if let Event::PaymentFailed { ref payment_hash, .. } = events[1] {
5987                         assert_eq!(*payment_hash, our_payment_hash);
5988                 } else { panic!("Unexpected event"); }
5989         }
5990 }
5991
5992 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5993 // There are only a few cases to test here:
5994 //  * its not really normative behavior, but we test that below-dust HTLCs "included" in
5995 //    broadcastable commitment transactions result in channel closure,
5996 //  * its included in an unrevoked-but-previous remote commitment transaction,
5997 //  * its included in the latest remote or local commitment transactions.
5998 // We test each of the three possible commitment transactions individually and use both dust and
5999 // non-dust HTLCs.
6000 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
6001 // assume they are handled the same across all six cases, as both outbound and inbound failures are
6002 // tested for at least one of the cases in other tests.
6003 #[test]
6004 fn htlc_claim_single_commitment_only_a() {
6005         do_htlc_claim_local_commitment_only(true);
6006         do_htlc_claim_local_commitment_only(false);
6007
6008         do_htlc_claim_current_remote_commitment_only(true);
6009         do_htlc_claim_current_remote_commitment_only(false);
6010 }
6011
6012 #[test]
6013 fn htlc_claim_single_commitment_only_b() {
6014         do_htlc_claim_previous_remote_commitment_only(true, false);
6015         do_htlc_claim_previous_remote_commitment_only(false, false);
6016         do_htlc_claim_previous_remote_commitment_only(true, true);
6017         do_htlc_claim_previous_remote_commitment_only(false, true);
6018 }
6019
6020 #[test]
6021 #[should_panic]
6022 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
6023         let chanmon_cfgs = create_chanmon_cfgs(2);
6024         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6025         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6026         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6027         // Force duplicate randomness for every get-random call
6028         for node in nodes.iter() {
6029                 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
6030         }
6031
6032         // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
6033         let channel_value_satoshis=10000;
6034         let push_msat=10001;
6035         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
6036         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6037         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
6038         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
6039
6040         // Create a second channel with the same random values. This used to panic due to a colliding
6041         // channel_id, but now panics due to a colliding outbound SCID alias.
6042         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6043 }
6044
6045 #[test]
6046 fn bolt2_open_channel_sending_node_checks_part2() {
6047         let chanmon_cfgs = create_chanmon_cfgs(2);
6048         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6049         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6050         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6051
6052         // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
6053         let channel_value_satoshis=2^24;
6054         let push_msat=10001;
6055         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6056
6057         // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
6058         let channel_value_satoshis=10000;
6059         // Test when push_msat is equal to 1000 * funding_satoshis.
6060         let push_msat=1000*channel_value_satoshis+1;
6061         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6062
6063         // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
6064         let channel_value_satoshis=10000;
6065         let push_msat=10001;
6066         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
6067         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6068         assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
6069
6070         // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
6071         // 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
6072         assert!(node0_to_1_send_open_channel.channel_flags<=1);
6073
6074         // 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.
6075         assert!(BREAKDOWN_TIMEOUT>0);
6076         assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
6077
6078         // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
6079         let chain_hash=genesis_block(Network::Testnet).header.block_hash();
6080         assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
6081
6082         // 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.
6083         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
6084         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
6085         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
6086         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
6087         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
6088 }
6089
6090 #[test]
6091 fn bolt2_open_channel_sane_dust_limit() {
6092         let chanmon_cfgs = create_chanmon_cfgs(2);
6093         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6094         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6095         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6096
6097         let channel_value_satoshis=1000000;
6098         let push_msat=10001;
6099         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
6100         let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6101         node0_to_1_send_open_channel.dust_limit_satoshis = 547;
6102         node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
6103
6104         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
6105         let events = nodes[1].node.get_and_clear_pending_msg_events();
6106         let err_msg = match events[0] {
6107                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
6108                         msg.clone()
6109                 },
6110                 _ => panic!("Unexpected event"),
6111         };
6112         assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
6113 }
6114
6115 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
6116 // originated from our node, its failure is surfaced to the user. We trigger this failure to
6117 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
6118 // is no longer affordable once it's freed.
6119 #[test]
6120 fn test_fail_holding_cell_htlc_upon_free() {
6121         let chanmon_cfgs = create_chanmon_cfgs(2);
6122         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6123         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6124         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6125         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6126
6127         // First nodes[0] generates an update_fee, setting the channel's
6128         // pending_update_fee.
6129         {
6130                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6131                 *feerate_lock += 20;
6132         }
6133         nodes[0].node.timer_tick_occurred();
6134         check_added_monitors!(nodes[0], 1);
6135
6136         let events = nodes[0].node.get_and_clear_pending_msg_events();
6137         assert_eq!(events.len(), 1);
6138         let (update_msg, commitment_signed) = match events[0] {
6139                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6140                         (update_fee.as_ref(), commitment_signed)
6141                 },
6142                 _ => panic!("Unexpected event"),
6143         };
6144
6145         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6146
6147         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6148         let channel_reserve = chan_stat.channel_reserve_msat;
6149         let feerate = get_feerate!(nodes[0], chan.2);
6150         let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6151
6152         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6153         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6154         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6155
6156         // Send a payment which passes reserve checks but gets stuck in the holding cell.
6157         let our_payment_id = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6158         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6159         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6160
6161         // Flush the pending fee update.
6162         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6163         let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6164         check_added_monitors!(nodes[1], 1);
6165         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
6166         check_added_monitors!(nodes[0], 1);
6167
6168         // Upon receipt of the RAA, there will be an attempt to resend the holding cell
6169         // HTLC, but now that the fee has been raised the payment will now fail, causing
6170         // us to surface its failure to the user.
6171         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6172         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6173         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);
6174         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 {}",
6175                 hex::encode(our_payment_hash.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6176         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6177
6178         // Check that the payment failed to be sent out.
6179         let events = nodes[0].node.get_and_clear_pending_events();
6180         assert_eq!(events.len(), 1);
6181         match &events[0] {
6182                 &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, .. } => {
6183                         assert_eq!(our_payment_id, *payment_id.as_ref().unwrap());
6184                         assert_eq!(our_payment_hash.clone(), *payment_hash);
6185                         assert_eq!(*rejected_by_dest, false);
6186                         assert_eq!(*all_paths_failed, true);
6187                         assert_eq!(*network_update, None);
6188                         assert_eq!(*short_channel_id, None);
6189                         assert_eq!(*error_code, None);
6190                         assert_eq!(*error_data, None);
6191                 },
6192                 _ => panic!("Unexpected event"),
6193         }
6194 }
6195
6196 // Test that if multiple HTLCs are released from the holding cell and one is
6197 // valid but the other is no longer valid upon release, the valid HTLC can be
6198 // successfully completed while the other one fails as expected.
6199 #[test]
6200 fn test_free_and_fail_holding_cell_htlcs() {
6201         let chanmon_cfgs = create_chanmon_cfgs(2);
6202         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6203         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6204         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6205         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6206
6207         // First nodes[0] generates an update_fee, setting the channel's
6208         // pending_update_fee.
6209         {
6210                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6211                 *feerate_lock += 200;
6212         }
6213         nodes[0].node.timer_tick_occurred();
6214         check_added_monitors!(nodes[0], 1);
6215
6216         let events = nodes[0].node.get_and_clear_pending_msg_events();
6217         assert_eq!(events.len(), 1);
6218         let (update_msg, commitment_signed) = match events[0] {
6219                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6220                         (update_fee.as_ref(), commitment_signed)
6221                 },
6222                 _ => panic!("Unexpected event"),
6223         };
6224
6225         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6226
6227         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6228         let channel_reserve = chan_stat.channel_reserve_msat;
6229         let feerate = get_feerate!(nodes[0], chan.2);
6230         let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6231
6232         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6233         let amt_1 = 20000;
6234         let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors) - amt_1;
6235         let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
6236         let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
6237
6238         // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6239         nodes[0].node.send_payment(&route_1, payment_hash_1, &Some(payment_secret_1)).unwrap();
6240         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6241         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6242         let payment_id_2 = nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
6243         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6244         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6245
6246         // Flush the pending fee update.
6247         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6248         let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6249         check_added_monitors!(nodes[1], 1);
6250         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6251         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6252         check_added_monitors!(nodes[0], 2);
6253
6254         // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6255         // but now that the fee has been raised the second payment will now fail, causing us
6256         // to surface its failure to the user. The first payment should succeed.
6257         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6258         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6259         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);
6260         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 {}",
6261                 hex::encode(payment_hash_2.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6262         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6263
6264         // Check that the second payment failed to be sent out.
6265         let events = nodes[0].node.get_and_clear_pending_events();
6266         assert_eq!(events.len(), 1);
6267         match &events[0] {
6268                 &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, .. } => {
6269                         assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
6270                         assert_eq!(payment_hash_2.clone(), *payment_hash);
6271                         assert_eq!(*rejected_by_dest, false);
6272                         assert_eq!(*all_paths_failed, true);
6273                         assert_eq!(*network_update, None);
6274                         assert_eq!(*short_channel_id, None);
6275                         assert_eq!(*error_code, None);
6276                         assert_eq!(*error_data, None);
6277                 },
6278                 _ => panic!("Unexpected event"),
6279         }
6280
6281         // Complete the first payment and the RAA from the fee update.
6282         let (payment_event, send_raa_event) = {
6283                 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6284                 assert_eq!(msgs.len(), 2);
6285                 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6286         };
6287         let raa = match send_raa_event {
6288                 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6289                 _ => panic!("Unexpected event"),
6290         };
6291         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6292         check_added_monitors!(nodes[1], 1);
6293         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6294         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6295         let events = nodes[1].node.get_and_clear_pending_events();
6296         assert_eq!(events.len(), 1);
6297         match events[0] {
6298                 Event::PendingHTLCsForwardable { .. } => {},
6299                 _ => panic!("Unexpected event"),
6300         }
6301         nodes[1].node.process_pending_htlc_forwards();
6302         let events = nodes[1].node.get_and_clear_pending_events();
6303         assert_eq!(events.len(), 1);
6304         match events[0] {
6305                 Event::PaymentReceived { .. } => {},
6306                 _ => panic!("Unexpected event"),
6307         }
6308         nodes[1].node.claim_funds(payment_preimage_1);
6309         check_added_monitors!(nodes[1], 1);
6310         let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6311         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6312         commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6313         expect_payment_sent!(nodes[0], payment_preimage_1);
6314 }
6315
6316 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6317 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6318 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6319 // once it's freed.
6320 #[test]
6321 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6322         let chanmon_cfgs = create_chanmon_cfgs(3);
6323         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6324         // When this test was written, the default base fee floated based on the HTLC count.
6325         // It is now fixed, so we simply set the fee to the expected value here.
6326         let mut config = test_default_channel_config();
6327         config.channel_options.forwarding_fee_base_msat = 196;
6328         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
6329         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6330         let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6331         let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6332
6333         // First nodes[1] generates an update_fee, setting the channel's
6334         // pending_update_fee.
6335         {
6336                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
6337                 *feerate_lock += 20;
6338         }
6339         nodes[1].node.timer_tick_occurred();
6340         check_added_monitors!(nodes[1], 1);
6341
6342         let events = nodes[1].node.get_and_clear_pending_msg_events();
6343         assert_eq!(events.len(), 1);
6344         let (update_msg, commitment_signed) = match events[0] {
6345                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6346                         (update_fee.as_ref(), commitment_signed)
6347                 },
6348                 _ => panic!("Unexpected event"),
6349         };
6350
6351         nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6352
6353         let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
6354         let channel_reserve = chan_stat.channel_reserve_msat;
6355         let feerate = get_feerate!(nodes[0], chan_0_1.2);
6356         let opt_anchors = get_opt_anchors!(nodes[0], chan_0_1.2);
6357
6358         // Send a payment which passes reserve checks but gets stuck in the holding cell.
6359         let feemsat = 239;
6360         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
6361         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors) - total_routing_fee_msat;
6362         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
6363         let payment_event = {
6364                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6365                 check_added_monitors!(nodes[0], 1);
6366
6367                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6368                 assert_eq!(events.len(), 1);
6369
6370                 SendEvent::from_event(events.remove(0))
6371         };
6372         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6373         check_added_monitors!(nodes[1], 0);
6374         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6375         expect_pending_htlcs_forwardable!(nodes[1]);
6376
6377         chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
6378         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6379
6380         // Flush the pending fee update.
6381         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6382         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6383         check_added_monitors!(nodes[2], 1);
6384         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6385         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6386         check_added_monitors!(nodes[1], 2);
6387
6388         // A final RAA message is generated to finalize the fee update.
6389         let events = nodes[1].node.get_and_clear_pending_msg_events();
6390         assert_eq!(events.len(), 1);
6391
6392         let raa_msg = match &events[0] {
6393                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6394                         msg.clone()
6395                 },
6396                 _ => panic!("Unexpected event"),
6397         };
6398
6399         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6400         check_added_monitors!(nodes[2], 1);
6401         assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6402
6403         // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6404         let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6405         assert_eq!(process_htlc_forwards_event.len(), 1);
6406         match &process_htlc_forwards_event[0] {
6407                 &Event::PendingHTLCsForwardable { .. } => {},
6408                 _ => panic!("Unexpected event"),
6409         }
6410
6411         // In response, we call ChannelManager's process_pending_htlc_forwards
6412         nodes[1].node.process_pending_htlc_forwards();
6413         check_added_monitors!(nodes[1], 1);
6414
6415         // This causes the HTLC to be failed backwards.
6416         let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6417         assert_eq!(fail_event.len(), 1);
6418         let (fail_msg, commitment_signed) = match &fail_event[0] {
6419                 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6420                         assert_eq!(updates.update_add_htlcs.len(), 0);
6421                         assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6422                         assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6423                         assert_eq!(updates.update_fail_htlcs.len(), 1);
6424                         (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6425                 },
6426                 _ => panic!("Unexpected event"),
6427         };
6428
6429         // Pass the failure messages back to nodes[0].
6430         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6431         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6432
6433         // Complete the HTLC failure+removal process.
6434         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6435         check_added_monitors!(nodes[0], 1);
6436         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6437         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6438         check_added_monitors!(nodes[1], 2);
6439         let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6440         assert_eq!(final_raa_event.len(), 1);
6441         let raa = match &final_raa_event[0] {
6442                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6443                 _ => panic!("Unexpected event"),
6444         };
6445         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6446         expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6447         check_added_monitors!(nodes[0], 1);
6448 }
6449
6450 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6451 // 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.
6452 //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.
6453
6454 #[test]
6455 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6456         //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6457         let chanmon_cfgs = create_chanmon_cfgs(2);
6458         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6459         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6460         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6461         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6462
6463         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6464         route.paths[0][0].fee_msat = 100;
6465
6466         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6467                 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6468         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6469         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6470 }
6471
6472 #[test]
6473 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6474         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6475         let chanmon_cfgs = create_chanmon_cfgs(2);
6476         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6477         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6478         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6479         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6480
6481         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6482         route.paths[0][0].fee_msat = 0;
6483         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6484                 assert_eq!(err, "Cannot send 0-msat HTLC"));
6485
6486         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6487         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6488 }
6489
6490 #[test]
6491 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6492         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6493         let chanmon_cfgs = create_chanmon_cfgs(2);
6494         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6495         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6496         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6497         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6498
6499         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6500         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6501         check_added_monitors!(nodes[0], 1);
6502         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6503         updates.update_add_htlcs[0].amount_msat = 0;
6504
6505         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6506         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6507         check_closed_broadcast!(nodes[1], true).unwrap();
6508         check_added_monitors!(nodes[1], 1);
6509         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
6510 }
6511
6512 #[test]
6513 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6514         //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6515         //It is enforced when constructing a route.
6516         let chanmon_cfgs = create_chanmon_cfgs(2);
6517         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6518         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6519         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6520         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6521
6522         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
6523                 .with_features(InvoiceFeatures::known());
6524         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000, 0);
6525         route.paths[0].last_mut().unwrap().cltv_expiry_delta = 500000001;
6526         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::RouteError { ref err },
6527                 assert_eq!(err, &"Channel CLTV overflowed?"));
6528 }
6529
6530 #[test]
6531 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6532         //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.
6533         //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6534         //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6535         let chanmon_cfgs = create_chanmon_cfgs(2);
6536         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6537         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6538         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6539         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6540         let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6541
6542         for i in 0..max_accepted_htlcs {
6543                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6544                 let payment_event = {
6545                         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6546                         check_added_monitors!(nodes[0], 1);
6547
6548                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6549                         assert_eq!(events.len(), 1);
6550                         if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6551                                 assert_eq!(htlcs[0].htlc_id, i);
6552                         } else {
6553                                 assert!(false);
6554                         }
6555                         SendEvent::from_event(events.remove(0))
6556                 };
6557                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6558                 check_added_monitors!(nodes[1], 0);
6559                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6560
6561                 expect_pending_htlcs_forwardable!(nodes[1]);
6562                 expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6563         }
6564         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6565         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6566                 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6567
6568         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6569         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6570 }
6571
6572 #[test]
6573 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6574         //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.
6575         let chanmon_cfgs = create_chanmon_cfgs(2);
6576         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6577         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6578         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6579         let channel_value = 100000;
6580         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::known(), InitFeatures::known());
6581         let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6582
6583         send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6584
6585         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6586         // Manually create a route over our max in flight (which our router normally automatically
6587         // limits us to.
6588         route.paths[0][0].fee_msat =  max_in_flight + 1;
6589         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6590                 assert!(regex::Regex::new(r"Cannot send value that would put us over the max HTLC value in flight our peer will accept \(\d+\)").unwrap().is_match(err)));
6591
6592         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6593         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send value that would put us over the max HTLC value in flight our peer will accept".to_string(), 1);
6594
6595         send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6596 }
6597
6598 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6599 #[test]
6600 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6601         //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6602         let chanmon_cfgs = create_chanmon_cfgs(2);
6603         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6604         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6605         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6606         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6607         let htlc_minimum_msat: u64;
6608         {
6609                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6610                 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6611                 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6612         }
6613
6614         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6615         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6616         check_added_monitors!(nodes[0], 1);
6617         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6618         updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6619         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6620         assert!(nodes[1].node.list_channels().is_empty());
6621         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6622         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()));
6623         check_added_monitors!(nodes[1], 1);
6624         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6625 }
6626
6627 #[test]
6628 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6629         //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
6630         let chanmon_cfgs = create_chanmon_cfgs(2);
6631         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6632         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6633         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6634         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6635
6636         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6637         let channel_reserve = chan_stat.channel_reserve_msat;
6638         let feerate = get_feerate!(nodes[0], chan.2);
6639         let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6640         // The 2* and +1 are for the fee spike reserve.
6641         let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6642
6643         let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6644         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6645         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6646         check_added_monitors!(nodes[0], 1);
6647         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6648
6649         // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6650         // at this time channel-initiatee receivers are not required to enforce that senders
6651         // respect the fee_spike_reserve.
6652         updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6653         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6654
6655         assert!(nodes[1].node.list_channels().is_empty());
6656         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6657         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6658         check_added_monitors!(nodes[1], 1);
6659         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6660 }
6661
6662 #[test]
6663 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6664         //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6665         //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6666         let chanmon_cfgs = create_chanmon_cfgs(2);
6667         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6668         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6669         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6670         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6671
6672         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3999999);
6673         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6674         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6675         let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6676         let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &Some(our_payment_secret), cur_height, &None).unwrap();
6677         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6678
6679         let mut msg = msgs::UpdateAddHTLC {
6680                 channel_id: chan.2,
6681                 htlc_id: 0,
6682                 amount_msat: 1000,
6683                 payment_hash: our_payment_hash,
6684                 cltv_expiry: htlc_cltv,
6685                 onion_routing_packet: onion_packet.clone(),
6686         };
6687
6688         for i in 0..super::channel::OUR_MAX_HTLCS {
6689                 msg.htlc_id = i as u64;
6690                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6691         }
6692         msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6693         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6694
6695         assert!(nodes[1].node.list_channels().is_empty());
6696         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6697         assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6698         check_added_monitors!(nodes[1], 1);
6699         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6700 }
6701
6702 #[test]
6703 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6704         //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6705         let chanmon_cfgs = create_chanmon_cfgs(2);
6706         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6707         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6708         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6709         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6710
6711         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6712         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6713         check_added_monitors!(nodes[0], 1);
6714         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6715         updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6716         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6717
6718         assert!(nodes[1].node.list_channels().is_empty());
6719         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6720         assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6721         check_added_monitors!(nodes[1], 1);
6722         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6723 }
6724
6725 #[test]
6726 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6727         //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6728         let chanmon_cfgs = create_chanmon_cfgs(2);
6729         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6730         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6731         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6732
6733         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6734         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6735         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6736         check_added_monitors!(nodes[0], 1);
6737         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6738         updates.update_add_htlcs[0].cltv_expiry = 500000000;
6739         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6740
6741         assert!(nodes[1].node.list_channels().is_empty());
6742         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6743         assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6744         check_added_monitors!(nodes[1], 1);
6745         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6746 }
6747
6748 #[test]
6749 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6750         //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6751         // We test this by first testing that that repeated HTLCs pass commitment signature checks
6752         // after disconnect and that non-sequential htlc_ids result in a channel failure.
6753         let chanmon_cfgs = create_chanmon_cfgs(2);
6754         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6755         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6756         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6757
6758         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6759         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6760         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6761         check_added_monitors!(nodes[0], 1);
6762         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6763         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6764
6765         //Disconnect and Reconnect
6766         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6767         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6768         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
6769         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6770         assert_eq!(reestablish_1.len(), 1);
6771         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
6772         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6773         assert_eq!(reestablish_2.len(), 1);
6774         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6775         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6776         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6777         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6778
6779         //Resend HTLC
6780         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6781         assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6782         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6783         check_added_monitors!(nodes[1], 1);
6784         let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6785
6786         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6787
6788         assert!(nodes[1].node.list_channels().is_empty());
6789         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6790         assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6791         check_added_monitors!(nodes[1], 1);
6792         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6793 }
6794
6795 #[test]
6796 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6797         //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.
6798
6799         let chanmon_cfgs = create_chanmon_cfgs(2);
6800         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6801         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6802         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6803         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6804         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6805         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6806
6807         check_added_monitors!(nodes[0], 1);
6808         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6809         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6810
6811         let update_msg = msgs::UpdateFulfillHTLC{
6812                 channel_id: chan.2,
6813                 htlc_id: 0,
6814                 payment_preimage: our_payment_preimage,
6815         };
6816
6817         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6818
6819         assert!(nodes[0].node.list_channels().is_empty());
6820         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6821         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()));
6822         check_added_monitors!(nodes[0], 1);
6823         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6824 }
6825
6826 #[test]
6827 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6828         //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.
6829
6830         let chanmon_cfgs = create_chanmon_cfgs(2);
6831         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6832         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6833         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6834         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6835
6836         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6837         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6838         check_added_monitors!(nodes[0], 1);
6839         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6840         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6841
6842         let update_msg = msgs::UpdateFailHTLC{
6843                 channel_id: chan.2,
6844                 htlc_id: 0,
6845                 reason: msgs::OnionErrorPacket { data: Vec::new()},
6846         };
6847
6848         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6849
6850         assert!(nodes[0].node.list_channels().is_empty());
6851         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6852         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()));
6853         check_added_monitors!(nodes[0], 1);
6854         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6855 }
6856
6857 #[test]
6858 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6859         //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.
6860
6861         let chanmon_cfgs = create_chanmon_cfgs(2);
6862         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6863         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6864         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6865         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6866
6867         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6868         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6869         check_added_monitors!(nodes[0], 1);
6870         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6871         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6872         let update_msg = msgs::UpdateFailMalformedHTLC{
6873                 channel_id: chan.2,
6874                 htlc_id: 0,
6875                 sha256_of_onion: [1; 32],
6876                 failure_code: 0x8000,
6877         };
6878
6879         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6880
6881         assert!(nodes[0].node.list_channels().is_empty());
6882         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6883         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()));
6884         check_added_monitors!(nodes[0], 1);
6885         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6886 }
6887
6888 #[test]
6889 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6890         //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6891
6892         let chanmon_cfgs = create_chanmon_cfgs(2);
6893         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6894         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6895         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6896         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6897
6898         let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6899
6900         nodes[1].node.claim_funds(our_payment_preimage);
6901         check_added_monitors!(nodes[1], 1);
6902
6903         let events = nodes[1].node.get_and_clear_pending_msg_events();
6904         assert_eq!(events.len(), 1);
6905         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6906                 match events[0] {
6907                         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, .. } } => {
6908                                 assert!(update_add_htlcs.is_empty());
6909                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6910                                 assert!(update_fail_htlcs.is_empty());
6911                                 assert!(update_fail_malformed_htlcs.is_empty());
6912                                 assert!(update_fee.is_none());
6913                                 update_fulfill_htlcs[0].clone()
6914                         },
6915                         _ => panic!("Unexpected event"),
6916                 }
6917         };
6918
6919         update_fulfill_msg.htlc_id = 1;
6920
6921         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6922
6923         assert!(nodes[0].node.list_channels().is_empty());
6924         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6925         assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6926         check_added_monitors!(nodes[0], 1);
6927         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6928 }
6929
6930 #[test]
6931 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6932         //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.
6933
6934         let chanmon_cfgs = create_chanmon_cfgs(2);
6935         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6936         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6937         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6938         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6939
6940         let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6941
6942         nodes[1].node.claim_funds(our_payment_preimage);
6943         check_added_monitors!(nodes[1], 1);
6944
6945         let events = nodes[1].node.get_and_clear_pending_msg_events();
6946         assert_eq!(events.len(), 1);
6947         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6948                 match events[0] {
6949                         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, .. } } => {
6950                                 assert!(update_add_htlcs.is_empty());
6951                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6952                                 assert!(update_fail_htlcs.is_empty());
6953                                 assert!(update_fail_malformed_htlcs.is_empty());
6954                                 assert!(update_fee.is_none());
6955                                 update_fulfill_htlcs[0].clone()
6956                         },
6957                         _ => panic!("Unexpected event"),
6958                 }
6959         };
6960
6961         update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6962
6963         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6964
6965         assert!(nodes[0].node.list_channels().is_empty());
6966         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6967         assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6968         check_added_monitors!(nodes[0], 1);
6969         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6970 }
6971
6972 #[test]
6973 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6974         //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.
6975
6976         let chanmon_cfgs = create_chanmon_cfgs(2);
6977         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6978         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6979         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6980         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6981
6982         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6983         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6984         check_added_monitors!(nodes[0], 1);
6985
6986         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6987         updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6988
6989         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6990         check_added_monitors!(nodes[1], 0);
6991         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6992
6993         let events = nodes[1].node.get_and_clear_pending_msg_events();
6994
6995         let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6996                 match events[0] {
6997                         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, .. } } => {
6998                                 assert!(update_add_htlcs.is_empty());
6999                                 assert!(update_fulfill_htlcs.is_empty());
7000                                 assert!(update_fail_htlcs.is_empty());
7001                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
7002                                 assert!(update_fee.is_none());
7003                                 update_fail_malformed_htlcs[0].clone()
7004                         },
7005                         _ => panic!("Unexpected event"),
7006                 }
7007         };
7008         update_msg.failure_code &= !0x8000;
7009         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
7010
7011         assert!(nodes[0].node.list_channels().is_empty());
7012         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
7013         assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
7014         check_added_monitors!(nodes[0], 1);
7015         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
7016 }
7017
7018 #[test]
7019 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
7020         //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
7021         //    * 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.
7022
7023         let chanmon_cfgs = create_chanmon_cfgs(3);
7024         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7025         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7026         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7027         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7028         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7029
7030         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
7031
7032         //First hop
7033         let mut payment_event = {
7034                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7035                 check_added_monitors!(nodes[0], 1);
7036                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7037                 assert_eq!(events.len(), 1);
7038                 SendEvent::from_event(events.remove(0))
7039         };
7040         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7041         check_added_monitors!(nodes[1], 0);
7042         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7043         expect_pending_htlcs_forwardable!(nodes[1]);
7044         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7045         assert_eq!(events_2.len(), 1);
7046         check_added_monitors!(nodes[1], 1);
7047         payment_event = SendEvent::from_event(events_2.remove(0));
7048         assert_eq!(payment_event.msgs.len(), 1);
7049
7050         //Second Hop
7051         payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
7052         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
7053         check_added_monitors!(nodes[2], 0);
7054         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
7055
7056         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
7057         assert_eq!(events_3.len(), 1);
7058         let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
7059                 match events_3[0] {
7060                         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 } } => {
7061                                 assert!(update_add_htlcs.is_empty());
7062                                 assert!(update_fulfill_htlcs.is_empty());
7063                                 assert!(update_fail_htlcs.is_empty());
7064                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
7065                                 assert!(update_fee.is_none());
7066                                 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
7067                         },
7068                         _ => panic!("Unexpected event"),
7069                 }
7070         };
7071
7072         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
7073
7074         check_added_monitors!(nodes[1], 0);
7075         commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
7076         expect_pending_htlcs_forwardable!(nodes[1]);
7077         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
7078         assert_eq!(events_4.len(), 1);
7079
7080         //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
7081         match events_4[0] {
7082                 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, .. } } => {
7083                         assert!(update_add_htlcs.is_empty());
7084                         assert!(update_fulfill_htlcs.is_empty());
7085                         assert_eq!(update_fail_htlcs.len(), 1);
7086                         assert!(update_fail_malformed_htlcs.is_empty());
7087                         assert!(update_fee.is_none());
7088                 },
7089                 _ => panic!("Unexpected event"),
7090         };
7091
7092         check_added_monitors!(nodes[1], 1);
7093 }
7094
7095 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
7096         // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
7097         // 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
7098         // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
7099
7100         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7101         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7102         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7103         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7104         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7105         let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7106
7107         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7108
7109         // We route 2 dust-HTLCs between A and B
7110         let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7111         let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7112         route_payment(&nodes[0], &[&nodes[1]], 1000000);
7113
7114         // Cache one local commitment tx as previous
7115         let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7116
7117         // Fail one HTLC to prune it in the will-be-latest-local commitment tx
7118         assert!(nodes[1].node.fail_htlc_backwards(&payment_hash_2));
7119         check_added_monitors!(nodes[1], 0);
7120         expect_pending_htlcs_forwardable!(nodes[1]);
7121         check_added_monitors!(nodes[1], 1);
7122
7123         let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7124         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
7125         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
7126         check_added_monitors!(nodes[0], 1);
7127
7128         // Cache one local commitment tx as lastest
7129         let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7130
7131         let events = nodes[0].node.get_and_clear_pending_msg_events();
7132         match events[0] {
7133                 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
7134                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7135                 },
7136                 _ => panic!("Unexpected event"),
7137         }
7138         match events[1] {
7139                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
7140                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7141                 },
7142                 _ => panic!("Unexpected event"),
7143         }
7144
7145         assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
7146         // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7147         if announce_latest {
7148                 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
7149         } else {
7150                 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
7151         }
7152
7153         check_closed_broadcast!(nodes[0], true);
7154         check_added_monitors!(nodes[0], 1);
7155         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7156
7157         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7158         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7159         let events = nodes[0].node.get_and_clear_pending_events();
7160         // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
7161         assert_eq!(events.len(), 2);
7162         let mut first_failed = false;
7163         for event in events {
7164                 match event {
7165                         Event::PaymentPathFailed { payment_hash, .. } => {
7166                                 if payment_hash == payment_hash_1 {
7167                                         assert!(!first_failed);
7168                                         first_failed = true;
7169                                 } else {
7170                                         assert_eq!(payment_hash, payment_hash_2);
7171                                 }
7172                         }
7173                         _ => panic!("Unexpected event"),
7174                 }
7175         }
7176 }
7177
7178 #[test]
7179 fn test_failure_delay_dust_htlc_local_commitment() {
7180         do_test_failure_delay_dust_htlc_local_commitment(true);
7181         do_test_failure_delay_dust_htlc_local_commitment(false);
7182 }
7183
7184 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7185         // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7186         // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7187         // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7188         // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7189         // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7190         // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7191
7192         let chanmon_cfgs = create_chanmon_cfgs(3);
7193         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7194         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7195         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7196         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7197
7198         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7199
7200         let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7201         let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7202
7203         let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7204         let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7205
7206         // We revoked bs_commitment_tx
7207         if revoked {
7208                 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7209                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
7210         }
7211
7212         let mut timeout_tx = Vec::new();
7213         if local {
7214                 // We fail dust-HTLC 1 by broadcast of local commitment tx
7215                 mine_transaction(&nodes[0], &as_commitment_tx[0]);
7216                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7217                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7218                 expect_payment_failed!(nodes[0], dust_hash, true);
7219
7220                 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
7221                 check_closed_broadcast!(nodes[0], true);
7222                 check_added_monitors!(nodes[0], 1);
7223                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7224                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
7225                 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7226                 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7227                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7228                 mine_transaction(&nodes[0], &timeout_tx[0]);
7229                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7230                 expect_payment_failed!(nodes[0], non_dust_hash, true);
7231         } else {
7232                 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7233                 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
7234                 check_closed_broadcast!(nodes[0], true);
7235                 check_added_monitors!(nodes[0], 1);
7236                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7237                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7238                 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7239                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
7240                 if !revoked {
7241                         expect_payment_failed!(nodes[0], dust_hash, true);
7242                         assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7243                         // We fail non-dust-HTLC 2 by broadcast of local timeout tx on remote commitment tx
7244                         mine_transaction(&nodes[0], &timeout_tx[0]);
7245                         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7246                         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7247                         expect_payment_failed!(nodes[0], non_dust_hash, true);
7248                 } else {
7249                         // If revoked, both dust & non-dust HTLCs should have been failed after ANTI_REORG_DELAY confs of revoked
7250                         // commitment tx
7251                         let events = nodes[0].node.get_and_clear_pending_events();
7252                         assert_eq!(events.len(), 2);
7253                         let first;
7254                         match events[0] {
7255                                 Event::PaymentPathFailed { payment_hash, .. } => {
7256                                         if payment_hash == dust_hash { first = true; }
7257                                         else { first = false; }
7258                                 },
7259                                 _ => panic!("Unexpected event"),
7260                         }
7261                         match events[1] {
7262                                 Event::PaymentPathFailed { payment_hash, .. } => {
7263                                         if first { assert_eq!(payment_hash, non_dust_hash); }
7264                                         else { assert_eq!(payment_hash, dust_hash); }
7265                                 },
7266                                 _ => panic!("Unexpected event"),
7267                         }
7268                 }
7269         }
7270 }
7271
7272 #[test]
7273 fn test_sweep_outbound_htlc_failure_update() {
7274         do_test_sweep_outbound_htlc_failure_update(false, true);
7275         do_test_sweep_outbound_htlc_failure_update(false, false);
7276         do_test_sweep_outbound_htlc_failure_update(true, false);
7277 }
7278
7279 #[test]
7280 fn test_user_configurable_csv_delay() {
7281         // We test our channel constructors yield errors when we pass them absurd csv delay
7282
7283         let mut low_our_to_self_config = UserConfig::default();
7284         low_our_to_self_config.own_channel_config.our_to_self_delay = 6;
7285         let mut high_their_to_self_config = UserConfig::default();
7286         high_their_to_self_config.peer_channel_config_limits.their_to_self_delay = 100;
7287         let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7288         let chanmon_cfgs = create_chanmon_cfgs(2);
7289         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7290         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7291         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7292
7293         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7294         if let Err(error) = Channel::new_outbound(&&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) },
7295                 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), 1000000, 1000000, 0,
7296                 &low_our_to_self_config, 0, 42)
7297         {
7298                 match error {
7299                         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())); },
7300                         _ => panic!("Unexpected event"),
7301                 }
7302         } else { assert!(false) }
7303
7304         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7305         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7306         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7307         open_channel.to_self_delay = 200;
7308         if let Err(error) = Channel::new_from_req(&&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) },
7309                 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), &open_channel, 0,
7310                 &low_our_to_self_config, 0, &nodes[0].logger, 42)
7311         {
7312                 match error {
7313                         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()));  },
7314                         _ => panic!("Unexpected event"),
7315                 }
7316         } else { assert!(false); }
7317
7318         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7319         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7320         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()));
7321         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7322         accept_channel.to_self_delay = 200;
7323         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7324         let reason_msg;
7325         if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7326                 match action {
7327                         &ErrorAction::SendErrorMessage { ref msg } => {
7328                                 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()));
7329                                 reason_msg = msg.data.clone();
7330                         },
7331                         _ => { panic!(); }
7332                 }
7333         } else { panic!(); }
7334         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg });
7335
7336         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7337         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7338         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7339         open_channel.to_self_delay = 200;
7340         if let Err(error) = Channel::new_from_req(&&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) },
7341                 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), &open_channel, 0,
7342                 &high_their_to_self_config, 0, &nodes[0].logger, 42)
7343         {
7344                 match error {
7345                         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())); },
7346                         _ => panic!("Unexpected event"),
7347                 }
7348         } else { assert!(false); }
7349 }
7350
7351 #[test]
7352 fn test_data_loss_protect() {
7353         // We want to be sure that :
7354         // * we don't broadcast our Local Commitment Tx in case of fallen behind
7355         //   (but this is not quite true - we broadcast during Drop because chanmon is out of sync with chanmgr)
7356         // * we close channel in case of detecting other being fallen behind
7357         // * we are able to claim our own outputs thanks to to_remote being static
7358         // TODO: this test is incomplete and the data_loss_protect implementation is incomplete - see issue #775
7359         let persister;
7360         let logger;
7361         let fee_estimator;
7362         let tx_broadcaster;
7363         let chain_source;
7364         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7365         // We broadcast during Drop because chanmon is out of sync with chanmgr, which would cause a panic
7366         // during signing due to revoked tx
7367         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7368         let keys_manager = &chanmon_cfgs[0].keys_manager;
7369         let monitor;
7370         let node_state_0;
7371         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7372         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7373         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7374
7375         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7376
7377         // Cache node A state before any channel update
7378         let previous_node_state = nodes[0].node.encode();
7379         let mut previous_chain_monitor_state = test_utils::TestVecWriter(Vec::new());
7380         get_monitor!(nodes[0], chan.2).write(&mut previous_chain_monitor_state).unwrap();
7381
7382         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7383         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7384
7385         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7386         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7387
7388         // Restore node A from previous state
7389         logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7390         let mut chain_monitor = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut io::Cursor::new(previous_chain_monitor_state.0), keys_manager).unwrap().1;
7391         chain_source = test_utils::TestChainSource::new(Network::Testnet);
7392         tx_broadcaster = test_utils::TestBroadcaster { txn_broadcasted: Mutex::new(Vec::new()), blocks: Arc::new(Mutex::new(Vec::new())) };
7393         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
7394         persister = test_utils::TestPersister::new();
7395         monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &tx_broadcaster, &logger, &fee_estimator, &persister, keys_manager);
7396         node_state_0 = {
7397                 let mut channel_monitors = HashMap::new();
7398                 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chain_monitor);
7399                 <(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 {
7400                         keys_manager: keys_manager,
7401                         fee_estimator: &fee_estimator,
7402                         chain_monitor: &monitor,
7403                         logger: &logger,
7404                         tx_broadcaster: &tx_broadcaster,
7405                         default_config: UserConfig::default(),
7406                         channel_monitors,
7407                 }).unwrap().1
7408         };
7409         nodes[0].node = &node_state_0;
7410         assert!(monitor.watch_channel(OutPoint { txid: chan.3.txid(), index: 0 }, chain_monitor).is_ok());
7411         nodes[0].chain_monitor = &monitor;
7412         nodes[0].chain_source = &chain_source;
7413
7414         check_added_monitors!(nodes[0], 1);
7415
7416         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7417         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7418
7419         let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7420
7421         // Check we don't broadcast any transactions following learning of per_commitment_point from B
7422         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7423         check_added_monitors!(nodes[0], 1);
7424
7425         {
7426                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7427                 assert_eq!(node_txn.len(), 0);
7428         }
7429
7430         let mut reestablish_1 = Vec::with_capacity(1);
7431         for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7432                 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
7433                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7434                         reestablish_1.push(msg.clone());
7435                 } else if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7436                 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7437                         match action {
7438                                 &ErrorAction::SendErrorMessage { ref msg } => {
7439                                         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");
7440                                 },
7441                                 _ => panic!("Unexpected event!"),
7442                         }
7443                 } else {
7444                         panic!("Unexpected event")
7445                 }
7446         }
7447
7448         // Check we close channel detecting A is fallen-behind
7449         // Check that we sent the warning message when we detected that A has fallen behind,
7450         // and give the possibility for A to recover from the warning.
7451         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7452         let warn_msg = "Peer attempted to reestablish channel with a very old local commitment transaction".to_owned();
7453         assert!(check_warn_msg!(nodes[1], nodes[0].node.get_our_node_id(), chan.2).contains(&warn_msg));
7454
7455         // Check A is able to claim to_remote output
7456         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7457         // The node B should not broadcast the transaction to force close the channel!
7458         assert!(node_txn.is_empty());
7459         // B should now detect that there is something wrong and should force close the channel.
7460         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";
7461         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: exp_err.to_string() });
7462
7463         // after the warning message sent by B, we should not able to
7464         // use the channel, or reconnect with success to the channel.
7465         assert!(nodes[0].node.list_usable_channels().is_empty());
7466         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7467         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7468         let retry_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7469
7470         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &retry_reestablish[0]);
7471         let mut err_msgs_0 = Vec::with_capacity(1);
7472         for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7473                 if let MessageSendEvent::HandleError { ref action, .. } = msg {
7474                         match action {
7475                                 &ErrorAction::SendErrorMessage { ref msg } => {
7476                                         assert_eq!(msg.data, "Failed to find corresponding channel");
7477                                         err_msgs_0.push(msg.clone());
7478                                 },
7479                                 _ => panic!("Unexpected event!"),
7480                         }
7481                 } else {
7482                         panic!("Unexpected event!");
7483                 }
7484         }
7485         assert_eq!(err_msgs_0.len(), 1);
7486         nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), &err_msgs_0[0]);
7487         assert!(nodes[1].node.list_usable_channels().is_empty());
7488         check_added_monitors!(nodes[1], 1);
7489         check_closed_event!(nodes[1], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "Failed to find corresponding channel".to_owned() });
7490         check_closed_broadcast!(nodes[1], false);
7491 }
7492
7493 #[test]
7494 fn test_check_htlc_underpaying() {
7495         // Send payment through A -> B but A is maliciously
7496         // sending a probe payment (i.e less than expected value0
7497         // to B, B should refuse payment.
7498
7499         let chanmon_cfgs = create_chanmon_cfgs(2);
7500         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7501         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7502         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7503
7504         // Create some initial channels
7505         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7506
7507         let scorer = test_utils::TestScorer::with_penalty(0);
7508         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7509         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7510         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();
7511         let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7512         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200).unwrap();
7513         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7514         check_added_monitors!(nodes[0], 1);
7515
7516         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7517         assert_eq!(events.len(), 1);
7518         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7519         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7520         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7521
7522         // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7523         // and then will wait a second random delay before failing the HTLC back:
7524         expect_pending_htlcs_forwardable!(nodes[1]);
7525         expect_pending_htlcs_forwardable!(nodes[1]);
7526
7527         // Node 3 is expecting payment of 100_000 but received 10_000,
7528         // it should fail htlc like we didn't know the preimage.
7529         nodes[1].node.process_pending_htlc_forwards();
7530
7531         let events = nodes[1].node.get_and_clear_pending_msg_events();
7532         assert_eq!(events.len(), 1);
7533         let (update_fail_htlc, commitment_signed) = match events[0] {
7534                 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 } } => {
7535                         assert!(update_add_htlcs.is_empty());
7536                         assert!(update_fulfill_htlcs.is_empty());
7537                         assert_eq!(update_fail_htlcs.len(), 1);
7538                         assert!(update_fail_malformed_htlcs.is_empty());
7539                         assert!(update_fee.is_none());
7540                         (update_fail_htlcs[0].clone(), commitment_signed)
7541                 },
7542                 _ => panic!("Unexpected event"),
7543         };
7544         check_added_monitors!(nodes[1], 1);
7545
7546         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7547         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7548
7549         // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7550         let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7551         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(CHAN_CONFIRM_DEPTH));
7552         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7553 }
7554
7555 #[test]
7556 fn test_announce_disable_channels() {
7557         // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7558         // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7559
7560         let chanmon_cfgs = create_chanmon_cfgs(2);
7561         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7562         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7563         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7564
7565         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7566         create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::known(), InitFeatures::known());
7567         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7568
7569         // Disconnect peers
7570         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7571         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7572
7573         nodes[0].node.timer_tick_occurred(); // Enabled -> DisabledStaged
7574         nodes[0].node.timer_tick_occurred(); // DisabledStaged -> Disabled
7575         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7576         assert_eq!(msg_events.len(), 3);
7577         let mut chans_disabled = HashMap::new();
7578         for e in msg_events {
7579                 match e {
7580                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7581                                 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7582                                 // Check that each channel gets updated exactly once
7583                                 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7584                                         panic!("Generated ChannelUpdate for wrong chan!");
7585                                 }
7586                         },
7587                         _ => panic!("Unexpected event"),
7588                 }
7589         }
7590         // Reconnect peers
7591         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7592         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7593         assert_eq!(reestablish_1.len(), 3);
7594         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7595         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7596         assert_eq!(reestablish_2.len(), 3);
7597
7598         // Reestablish chan_1
7599         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7600         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7601         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7602         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7603         // Reestablish chan_2
7604         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7605         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7606         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7607         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7608         // Reestablish chan_3
7609         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7610         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7611         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7612         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7613
7614         nodes[0].node.timer_tick_occurred();
7615         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7616         nodes[0].node.timer_tick_occurred();
7617         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7618         assert_eq!(msg_events.len(), 3);
7619         for e in msg_events {
7620                 match e {
7621                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7622                                 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7623                                 match chans_disabled.remove(&msg.contents.short_channel_id) {
7624                                         // Each update should have a higher timestamp than the previous one, replacing
7625                                         // the old one.
7626                                         Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7627                                         None => panic!("Generated ChannelUpdate for wrong chan!"),
7628                                 }
7629                         },
7630                         _ => panic!("Unexpected event"),
7631                 }
7632         }
7633         // Check that each channel gets updated exactly once
7634         assert!(chans_disabled.is_empty());
7635 }
7636
7637 #[test]
7638 fn test_bump_penalty_txn_on_revoked_commitment() {
7639         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7640         // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7641
7642         let chanmon_cfgs = create_chanmon_cfgs(2);
7643         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7644         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7645         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7646
7647         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7648
7649         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7650         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id())
7651                 .with_features(InvoiceFeatures::known());
7652         let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000, 30);
7653         send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7654
7655         let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7656         // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7657         assert_eq!(revoked_txn[0].output.len(), 4);
7658         assert_eq!(revoked_txn[0].input.len(), 1);
7659         assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7660         let revoked_txid = revoked_txn[0].txid();
7661
7662         let mut penalty_sum = 0;
7663         for outp in revoked_txn[0].output.iter() {
7664                 if outp.script_pubkey.is_v0_p2wsh() {
7665                         penalty_sum += outp.value;
7666                 }
7667         }
7668
7669         // Connect blocks to change height_timer range to see if we use right soonest_timelock
7670         let header_114 = connect_blocks(&nodes[1], 14);
7671
7672         // Actually revoke tx by claiming a HTLC
7673         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7674         let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7675         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] });
7676         check_added_monitors!(nodes[1], 1);
7677
7678         // One or more justice tx should have been broadcast, check it
7679         let penalty_1;
7680         let feerate_1;
7681         {
7682                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7683                 assert_eq!(node_txn.len(), 2); // justice tx (broadcasted from ChannelMonitor) + local commitment tx
7684                 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7685                 assert_eq!(node_txn[0].output.len(), 1);
7686                 check_spends!(node_txn[0], revoked_txn[0]);
7687                 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7688                 feerate_1 = fee_1 * 1000 / node_txn[0].weight() as u64;
7689                 penalty_1 = node_txn[0].txid();
7690                 node_txn.clear();
7691         };
7692
7693         // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7694         connect_blocks(&nodes[1], 15);
7695         let mut penalty_2 = penalty_1;
7696         let mut feerate_2 = 0;
7697         {
7698                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7699                 assert_eq!(node_txn.len(), 1);
7700                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7701                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7702                         assert_eq!(node_txn[0].output.len(), 1);
7703                         check_spends!(node_txn[0], revoked_txn[0]);
7704                         penalty_2 = node_txn[0].txid();
7705                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7706                         assert_ne!(penalty_2, penalty_1);
7707                         let fee_2 = penalty_sum - node_txn[0].output[0].value;
7708                         feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7709                         // Verify 25% bump heuristic
7710                         assert!(feerate_2 * 100 >= feerate_1 * 125);
7711                         node_txn.clear();
7712                 }
7713         }
7714         assert_ne!(feerate_2, 0);
7715
7716         // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7717         connect_blocks(&nodes[1], 1);
7718         let penalty_3;
7719         let mut feerate_3 = 0;
7720         {
7721                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7722                 assert_eq!(node_txn.len(), 1);
7723                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7724                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7725                         assert_eq!(node_txn[0].output.len(), 1);
7726                         check_spends!(node_txn[0], revoked_txn[0]);
7727                         penalty_3 = node_txn[0].txid();
7728                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7729                         assert_ne!(penalty_3, penalty_2);
7730                         let fee_3 = penalty_sum - node_txn[0].output[0].value;
7731                         feerate_3 = fee_3 * 1000 / node_txn[0].weight() as u64;
7732                         // Verify 25% bump heuristic
7733                         assert!(feerate_3 * 100 >= feerate_2 * 125);
7734                         node_txn.clear();
7735                 }
7736         }
7737         assert_ne!(feerate_3, 0);
7738
7739         nodes[1].node.get_and_clear_pending_events();
7740         nodes[1].node.get_and_clear_pending_msg_events();
7741 }
7742
7743 #[test]
7744 fn test_bump_penalty_txn_on_revoked_htlcs() {
7745         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7746         // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7747
7748         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7749         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7750         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7751         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7752         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7753
7754         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7755         // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7756         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7757         let scorer = test_utils::TestScorer::with_penalty(0);
7758         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7759         let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None,
7760                 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7761         let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7762         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7763         let route = get_route(&nodes[1].node.get_our_node_id(), &payment_params, &nodes[1].network_graph.read_only(), None,
7764                 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7765         send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7766
7767         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7768         assert_eq!(revoked_local_txn[0].input.len(), 1);
7769         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7770
7771         // Revoke local commitment tx
7772         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7773
7774         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7775         // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7776         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] });
7777         check_closed_broadcast!(nodes[1], true);
7778         check_added_monitors!(nodes[1], 1);
7779         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7780         connect_blocks(&nodes[1], 49); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7781
7782         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7783         assert_eq!(revoked_htlc_txn.len(), 3);
7784         check_spends!(revoked_htlc_txn[1], chan.3);
7785
7786         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7787         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7788         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7789
7790         assert_eq!(revoked_htlc_txn[2].input.len(), 1);
7791         assert_eq!(revoked_htlc_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7792         assert_eq!(revoked_htlc_txn[2].output.len(), 1);
7793         check_spends!(revoked_htlc_txn[2], revoked_local_txn[0]);
7794
7795         // Broadcast set of revoked txn on A
7796         let hash_128 = connect_blocks(&nodes[0], 40);
7797         let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7798         connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] });
7799         let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7800         connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[2].clone()] });
7801         let events = nodes[0].node.get_and_clear_pending_events();
7802         expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7803         match events[1] {
7804                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7805                 _ => panic!("Unexpected event"),
7806         }
7807         let first;
7808         let feerate_1;
7809         let penalty_txn;
7810         {
7811                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7812                 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7813                 // Verify claim tx are spending revoked HTLC txn
7814
7815                 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7816                 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7817                 // which are included in the same block (they are broadcasted because we scan the
7818                 // transactions linearly and generate claims as we go, they likely should be removed in the
7819                 // future).
7820                 assert_eq!(node_txn[0].input.len(), 1);
7821                 check_spends!(node_txn[0], revoked_local_txn[0]);
7822                 assert_eq!(node_txn[1].input.len(), 1);
7823                 check_spends!(node_txn[1], revoked_local_txn[0]);
7824                 assert_eq!(node_txn[2].input.len(), 1);
7825                 check_spends!(node_txn[2], revoked_local_txn[0]);
7826
7827                 // Each of the three justice transactions claim a separate (single) output of the three
7828                 // available, which we check here:
7829                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7830                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7831                 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7832
7833                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7834                 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7835
7836                 // node_txn[3] is the local commitment tx broadcast just because (and somewhat in case of
7837                 // reorgs, though its not clear its ever worth broadcasting conflicting txn like this when
7838                 // a remote commitment tx has already been confirmed).
7839                 check_spends!(node_txn[3], chan.3);
7840
7841                 // node_txn[4] spends the revoked outputs from the revoked_htlc_txn (which only have one
7842                 // output, checked above).
7843                 assert_eq!(node_txn[4].input.len(), 2);
7844                 assert_eq!(node_txn[4].output.len(), 1);
7845                 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7846
7847                 first = node_txn[4].txid();
7848                 // Store both feerates for later comparison
7849                 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[4].output[0].value;
7850                 feerate_1 = fee_1 * 1000 / node_txn[4].weight() as u64;
7851                 penalty_txn = vec![node_txn[2].clone()];
7852                 node_txn.clear();
7853         }
7854
7855         // Connect one more block to see if bumped penalty are issued for HTLC txn
7856         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7857         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7858         let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7859         connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() });
7860         {
7861                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7862                 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7863
7864                 check_spends!(node_txn[0], revoked_local_txn[0]);
7865                 check_spends!(node_txn[1], revoked_local_txn[0]);
7866                 // Note that these are both bogus - they spend outputs already claimed in block 129:
7867                 if node_txn[0].input[0].previous_output == revoked_htlc_txn[0].input[0].previous_output  {
7868                         assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7869                 } else {
7870                         assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7871                         assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7872                 }
7873
7874                 node_txn.clear();
7875         };
7876
7877         // Few more blocks to confirm penalty txn
7878         connect_blocks(&nodes[0], 4);
7879         assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7880         let header_144 = connect_blocks(&nodes[0], 9);
7881         let node_txn = {
7882                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7883                 assert_eq!(node_txn.len(), 1);
7884
7885                 assert_eq!(node_txn[0].input.len(), 2);
7886                 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7887                 // Verify bumped tx is different and 25% bump heuristic
7888                 assert_ne!(first, node_txn[0].txid());
7889                 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[0].output[0].value;
7890                 let feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7891                 assert!(feerate_2 * 100 > feerate_1 * 125);
7892                 let txn = vec![node_txn[0].clone()];
7893                 node_txn.clear();
7894                 txn
7895         };
7896         // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7897         let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7898         connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn });
7899         connect_blocks(&nodes[0], 20);
7900         {
7901                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7902                 // We verify than no new transaction has been broadcast because previously
7903                 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7904                 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7905                 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7906                 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7907                 // up bumped justice generation.
7908                 assert_eq!(node_txn.len(), 0);
7909                 node_txn.clear();
7910         }
7911         check_closed_broadcast!(nodes[0], true);
7912         check_added_monitors!(nodes[0], 1);
7913 }
7914
7915 #[test]
7916 fn test_bump_penalty_txn_on_remote_commitment() {
7917         // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7918         // we're able to claim outputs on remote commitment transaction before timelocks expiration
7919
7920         // Create 2 HTLCs
7921         // Provide preimage for one
7922         // Check aggregation
7923
7924         let chanmon_cfgs = create_chanmon_cfgs(2);
7925         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7926         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7927         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7928
7929         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7930         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7931         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7932
7933         // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7934         let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7935         assert_eq!(remote_txn[0].output.len(), 4);
7936         assert_eq!(remote_txn[0].input.len(), 1);
7937         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7938
7939         // Claim a HTLC without revocation (provide B monitor with preimage)
7940         nodes[1].node.claim_funds(payment_preimage);
7941         mine_transaction(&nodes[1], &remote_txn[0]);
7942         check_added_monitors!(nodes[1], 2);
7943         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7944
7945         // One or more claim tx should have been broadcast, check it
7946         let timeout;
7947         let preimage;
7948         let preimage_bump;
7949         let feerate_timeout;
7950         let feerate_preimage;
7951         {
7952                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7953                 // 9 transactions including:
7954                 // 1*2 ChannelManager local broadcasts of commitment + HTLC-Success
7955                 // 1*3 ChannelManager local broadcasts of commitment + HTLC-Success + HTLC-Timeout
7956                 // 2 * HTLC-Success (one RBF bump we'll check later)
7957                 // 1 * HTLC-Timeout
7958                 assert_eq!(node_txn.len(), 8);
7959                 assert_eq!(node_txn[0].input.len(), 1);
7960                 assert_eq!(node_txn[6].input.len(), 1);
7961                 check_spends!(node_txn[0], remote_txn[0]);
7962                 check_spends!(node_txn[6], remote_txn[0]);
7963                 assert_eq!(node_txn[0].input[0].previous_output, node_txn[3].input[0].previous_output);
7964                 preimage_bump = node_txn[3].clone();
7965
7966                 check_spends!(node_txn[1], chan.3);
7967                 check_spends!(node_txn[2], node_txn[1]);
7968                 assert_eq!(node_txn[1], node_txn[4]);
7969                 assert_eq!(node_txn[2], node_txn[5]);
7970
7971                 timeout = node_txn[6].txid();
7972                 let index = node_txn[6].input[0].previous_output.vout;
7973                 let fee = remote_txn[0].output[index as usize].value - node_txn[6].output[0].value;
7974                 feerate_timeout = fee * 1000 / node_txn[6].weight() as u64;
7975
7976                 preimage = node_txn[0].txid();
7977                 let index = node_txn[0].input[0].previous_output.vout;
7978                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7979                 feerate_preimage = fee * 1000 / node_txn[0].weight() as u64;
7980
7981                 node_txn.clear();
7982         };
7983         assert_ne!(feerate_timeout, 0);
7984         assert_ne!(feerate_preimage, 0);
7985
7986         // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7987         connect_blocks(&nodes[1], 15);
7988         {
7989                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7990                 assert_eq!(node_txn.len(), 1);
7991                 assert_eq!(node_txn[0].input.len(), 1);
7992                 assert_eq!(preimage_bump.input.len(), 1);
7993                 check_spends!(node_txn[0], remote_txn[0]);
7994                 check_spends!(preimage_bump, remote_txn[0]);
7995
7996                 let index = preimage_bump.input[0].previous_output.vout;
7997                 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
7998                 let new_feerate = fee * 1000 / preimage_bump.weight() as u64;
7999                 assert!(new_feerate * 100 > feerate_timeout * 125);
8000                 assert_ne!(timeout, preimage_bump.txid());
8001
8002                 let index = node_txn[0].input[0].previous_output.vout;
8003                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8004                 let new_feerate = fee * 1000 / node_txn[0].weight() as u64;
8005                 assert!(new_feerate * 100 > feerate_preimage * 125);
8006                 assert_ne!(preimage, node_txn[0].txid());
8007
8008                 node_txn.clear();
8009         }
8010
8011         nodes[1].node.get_and_clear_pending_events();
8012         nodes[1].node.get_and_clear_pending_msg_events();
8013 }
8014
8015 #[test]
8016 fn test_counterparty_raa_skip_no_crash() {
8017         // Previously, if our counterparty sent two RAAs in a row without us having provided a
8018         // commitment transaction, we would have happily carried on and provided them the next
8019         // commitment transaction based on one RAA forward. This would probably eventually have led to
8020         // channel closure, but it would not have resulted in funds loss. Still, our
8021         // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
8022         // check simply that the channel is closed in response to such an RAA, but don't check whether
8023         // we decide to punish our counterparty for revoking their funds (as we don't currently
8024         // implement that).
8025         let chanmon_cfgs = create_chanmon_cfgs(2);
8026         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8027         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8028         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8029         let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
8030
8031         let mut guard = nodes[0].node.channel_state.lock().unwrap();
8032         let keys = guard.by_id.get_mut(&channel_id).unwrap().get_signer();
8033
8034         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
8035
8036         // Make signer believe we got a counterparty signature, so that it allows the revocation
8037         keys.get_enforcement_state().last_holder_commitment -= 1;
8038         let per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
8039
8040         // Must revoke without gaps
8041         keys.get_enforcement_state().last_holder_commitment -= 1;
8042         keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
8043
8044         keys.get_enforcement_state().last_holder_commitment -= 1;
8045         let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
8046                 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
8047
8048         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
8049                 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
8050         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
8051         check_added_monitors!(nodes[1], 1);
8052         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
8053 }
8054
8055 #[test]
8056 fn test_bump_txn_sanitize_tracking_maps() {
8057         // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
8058         // verify we clean then right after expiration of ANTI_REORG_DELAY.
8059
8060         let chanmon_cfgs = create_chanmon_cfgs(2);
8061         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8062         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8063         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8064
8065         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8066         // Lock HTLC in both directions
8067         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8068         route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
8069
8070         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
8071         assert_eq!(revoked_local_txn[0].input.len(), 1);
8072         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8073
8074         // Revoke local commitment tx
8075         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
8076
8077         // Broadcast set of revoked txn on A
8078         connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
8079         expect_pending_htlcs_forwardable_ignore!(nodes[0]);
8080         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
8081
8082         mine_transaction(&nodes[0], &revoked_local_txn[0]);
8083         check_closed_broadcast!(nodes[0], true);
8084         check_added_monitors!(nodes[0], 1);
8085         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8086         let penalty_txn = {
8087                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8088                 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
8089                 check_spends!(node_txn[0], revoked_local_txn[0]);
8090                 check_spends!(node_txn[1], revoked_local_txn[0]);
8091                 check_spends!(node_txn[2], revoked_local_txn[0]);
8092                 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
8093                 node_txn.clear();
8094                 penalty_txn
8095         };
8096         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8097         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
8098         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8099         {
8100                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
8101                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
8102                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
8103         }
8104 }
8105
8106 #[test]
8107 fn test_pending_claimed_htlc_no_balance_underflow() {
8108         // Tests that if we have a pending outbound HTLC as well as a claimed-but-not-fully-removed
8109         // HTLC we will not underflow when we call `Channel::get_balance_msat()`.
8110         let chanmon_cfgs = create_chanmon_cfgs(2);
8111         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8112         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8113         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8114         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
8115
8116         let payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 1_010_000).0;
8117         nodes[1].node.claim_funds(payment_preimage);
8118         check_added_monitors!(nodes[1], 1);
8119         let fulfill_ev = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8120
8121         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &fulfill_ev.update_fulfill_htlcs[0]);
8122         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
8123         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &fulfill_ev.commitment_signed);
8124         check_added_monitors!(nodes[0], 1);
8125         let (_raa, _cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
8126
8127         // At this point nodes[1] has received 1,010k msat (10k msat more than their reserve) and can
8128         // send an HTLC back (though it will go in the holding cell). Send an HTLC back and check we
8129         // can get our balance.
8130
8131         // Get a route from nodes[1] to nodes[0] by getting a route going the other way and then flip
8132         // the public key of the only hop. This works around ChannelDetails not showing the
8133         // almost-claimed HTLC as available balance.
8134         let (mut route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 10_000);
8135         route.payment_params = None; // This is all wrong, but unnecessary
8136         route.paths[0][0].pubkey = nodes[0].node.get_our_node_id();
8137         let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[0]);
8138         nodes[1].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
8139
8140         assert_eq!(nodes[1].node.list_channels()[0].balance_msat, 1_000_000);
8141 }
8142
8143 #[test]
8144 fn test_channel_conf_timeout() {
8145         // Tests that, for inbound channels, we give up on them if the funding transaction does not
8146         // confirm within 2016 blocks, as recommended by BOLT 2.
8147         let chanmon_cfgs = create_chanmon_cfgs(2);
8148         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8149         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8150         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8151
8152         let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000, InitFeatures::known(), InitFeatures::known());
8153
8154         // The outbound node should wait forever for confirmation:
8155         // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
8156         // copied here instead of directly referencing the constant.
8157         connect_blocks(&nodes[0], 2016);
8158         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8159
8160         // The inbound node should fail the channel after exactly 2016 blocks
8161         connect_blocks(&nodes[1], 2015);
8162         check_added_monitors!(nodes[1], 0);
8163         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8164
8165         connect_blocks(&nodes[1], 1);
8166         check_added_monitors!(nodes[1], 1);
8167         check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut);
8168         let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
8169         assert_eq!(close_ev.len(), 1);
8170         match close_ev[0] {
8171                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
8172                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8173                         assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
8174                 },
8175                 _ => panic!("Unexpected event"),
8176         }
8177 }
8178
8179 #[test]
8180 fn test_override_channel_config() {
8181         let chanmon_cfgs = create_chanmon_cfgs(2);
8182         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8183         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8184         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8185
8186         // Node0 initiates a channel to node1 using the override config.
8187         let mut override_config = UserConfig::default();
8188         override_config.own_channel_config.our_to_self_delay = 200;
8189
8190         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
8191
8192         // Assert the channel created by node0 is using the override config.
8193         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8194         assert_eq!(res.channel_flags, 0);
8195         assert_eq!(res.to_self_delay, 200);
8196 }
8197
8198 #[test]
8199 fn test_override_0msat_htlc_minimum() {
8200         let mut zero_config = UserConfig::default();
8201         zero_config.own_channel_config.our_htlc_minimum_msat = 0;
8202         let chanmon_cfgs = create_chanmon_cfgs(2);
8203         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8204         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
8205         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8206
8207         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
8208         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8209         assert_eq!(res.htlc_minimum_msat, 1);
8210
8211         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8212         let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8213         assert_eq!(res.htlc_minimum_msat, 1);
8214 }
8215
8216 #[test]
8217 fn test_channel_update_has_correct_htlc_maximum_msat() {
8218         // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
8219         // Bolt 7 specifies that if present `htlc_maximum_msat`:
8220         // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
8221         // 90% of the `channel_value`.
8222         // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
8223
8224         let mut config_30_percent = UserConfig::default();
8225         config_30_percent.channel_options.announced_channel = true;
8226         config_30_percent.own_channel_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
8227         let mut config_50_percent = UserConfig::default();
8228         config_50_percent.channel_options.announced_channel = true;
8229         config_50_percent.own_channel_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
8230         let mut config_95_percent = UserConfig::default();
8231         config_95_percent.channel_options.announced_channel = true;
8232         config_95_percent.own_channel_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
8233         let mut config_100_percent = UserConfig::default();
8234         config_100_percent.channel_options.announced_channel = true;
8235         config_100_percent.own_channel_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
8236
8237         let chanmon_cfgs = create_chanmon_cfgs(4);
8238         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8239         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)]);
8240         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8241
8242         let channel_value_satoshis = 100000;
8243         let channel_value_msat = channel_value_satoshis * 1000;
8244         let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
8245         let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
8246         let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
8247
8248         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());
8249         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());
8250
8251         // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
8252         // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
8253         assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, OptionalField::Present(channel_value_50_percent_msat));
8254         // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
8255         // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
8256         assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, OptionalField::Present(channel_value_30_percent_msat));
8257
8258         // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
8259         // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
8260         // `channel_value`.
8261         assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, OptionalField::Present(channel_value_90_percent_msat));
8262         // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
8263         // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
8264         // `channel_value`.
8265         assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, OptionalField::Present(channel_value_90_percent_msat));
8266 }
8267
8268 #[test]
8269 fn test_manually_accept_inbound_channel_request() {
8270         let mut manually_accept_conf = UserConfig::default();
8271         manually_accept_conf.manually_accept_inbound_channels = true;
8272         let chanmon_cfgs = create_chanmon_cfgs(2);
8273         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8274         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8275         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8276
8277         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8278         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8279
8280         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8281
8282         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8283         // accepting the inbound channel request.
8284         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8285
8286         let events = nodes[1].node.get_and_clear_pending_events();
8287         match events[0] {
8288                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8289                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
8290                 }
8291                 _ => panic!("Unexpected event"),
8292         }
8293
8294         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8295         assert_eq!(accept_msg_ev.len(), 1);
8296
8297         match accept_msg_ev[0] {
8298                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8299                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8300                 }
8301                 _ => panic!("Unexpected event"),
8302         }
8303
8304         nodes[1].node.force_close_channel(&temp_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
8305
8306         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8307         assert_eq!(close_msg_ev.len(), 1);
8308
8309         let events = nodes[1].node.get_and_clear_pending_events();
8310         match events[0] {
8311                 Event::ChannelClosed { user_channel_id, .. } => {
8312                         assert_eq!(user_channel_id, 23);
8313                 }
8314                 _ => panic!("Unexpected event"),
8315         }
8316 }
8317
8318 #[test]
8319 fn test_manually_reject_inbound_channel_request() {
8320         let mut manually_accept_conf = UserConfig::default();
8321         manually_accept_conf.manually_accept_inbound_channels = true;
8322         let chanmon_cfgs = create_chanmon_cfgs(2);
8323         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8324         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8325         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8326
8327         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8328         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8329
8330         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8331
8332         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8333         // rejecting the inbound channel request.
8334         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8335
8336         let events = nodes[1].node.get_and_clear_pending_events();
8337         match events[0] {
8338                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8339                         nodes[1].node.force_close_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
8340                 }
8341                 _ => panic!("Unexpected event"),
8342         }
8343
8344         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8345         assert_eq!(close_msg_ev.len(), 1);
8346
8347         match close_msg_ev[0] {
8348                 MessageSendEvent::HandleError { ref node_id, .. } => {
8349                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8350                 }
8351                 _ => panic!("Unexpected event"),
8352         }
8353         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
8354 }
8355
8356 #[test]
8357 fn test_reject_funding_before_inbound_channel_accepted() {
8358         // This tests that when `UserConfig::manually_accept_inbound_channels` is set to true, inbound
8359         // channels must to be manually accepted through `ChannelManager::accept_inbound_channel` by
8360         // the node operator before the counterparty sends a `FundingCreated` message. If a
8361         // `FundingCreated` message is received before the channel is accepted, it should be rejected
8362         // and the channel should be closed.
8363         let mut manually_accept_conf = UserConfig::default();
8364         manually_accept_conf.manually_accept_inbound_channels = true;
8365         let chanmon_cfgs = create_chanmon_cfgs(2);
8366         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8367         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8368         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8369
8370         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8371         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8372         let temp_channel_id = res.temporary_channel_id;
8373
8374         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8375
8376         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in the `msg_events`.
8377         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8378
8379         // Clear the `Event::OpenChannelRequest` event without responding to the request.
8380         nodes[1].node.get_and_clear_pending_events();
8381
8382         // Get the `AcceptChannel` message of `nodes[1]` without calling
8383         // `ChannelManager::accept_inbound_channel`, which generates a
8384         // `MessageSendEvent::SendAcceptChannel` event. The message is passed to `nodes[0]`
8385         // `handle_accept_channel`, which is required in order for `create_funding_transaction` to
8386         // succeed when `nodes[0]` is passed to it.
8387         {
8388                 let mut lock;
8389                 let channel = get_channel_ref!(&nodes[1], lock, temp_channel_id);
8390                 let accept_chan_msg = channel.get_accept_channel_message();
8391                 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8392         }
8393
8394         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8395
8396         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8397         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8398
8399         // The `funding_created_msg` should be rejected by `nodes[1]` as it hasn't accepted the channel
8400         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
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         let expected_err = "FundingCreated message received before the channel was accepted";
8406         match close_msg_ev[0] {
8407                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id, } => {
8408                         assert_eq!(msg.channel_id, temp_channel_id);
8409                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8410                         assert_eq!(msg.data, expected_err);
8411                 }
8412                 _ => panic!("Unexpected event"),
8413         }
8414
8415         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
8416 }
8417
8418 #[test]
8419 fn test_can_not_accept_inbound_channel_twice() {
8420         let mut manually_accept_conf = UserConfig::default();
8421         manually_accept_conf.manually_accept_inbound_channels = true;
8422         let chanmon_cfgs = create_chanmon_cfgs(2);
8423         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8424         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8425         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8426
8427         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8428         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8429
8430         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8431
8432         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8433         // accepting the inbound channel request.
8434         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8435
8436         let events = nodes[1].node.get_and_clear_pending_events();
8437         match events[0] {
8438                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8439                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
8440                         let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
8441                         match api_res {
8442                                 Err(APIError::APIMisuseError { err }) => {
8443                                         assert_eq!(err, "The channel isn't currently awaiting to be accepted.");
8444                                 },
8445                                 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
8446                                 Err(_) => panic!("Unexpected Error"),
8447                         }
8448                 }
8449                 _ => panic!("Unexpected event"),
8450         }
8451
8452         // Ensure that the channel wasn't closed after attempting to accept it twice.
8453         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8454         assert_eq!(accept_msg_ev.len(), 1);
8455
8456         match accept_msg_ev[0] {
8457                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8458                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8459                 }
8460                 _ => panic!("Unexpected event"),
8461         }
8462 }
8463
8464 #[test]
8465 fn test_can_not_accept_unknown_inbound_channel() {
8466         let chanmon_cfg = create_chanmon_cfgs(2);
8467         let node_cfg = create_node_cfgs(2, &chanmon_cfg);
8468         let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
8469         let nodes = create_network(2, &node_cfg, &node_chanmgr);
8470
8471         let unknown_channel_id = [0; 32];
8472         let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
8473         match api_res {
8474                 Err(APIError::ChannelUnavailable { err }) => {
8475                         assert_eq!(err, "Can't accept a channel that doesn't exist");
8476                 },
8477                 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
8478                 Err(_) => panic!("Unexpected Error"),
8479         }
8480 }
8481
8482 #[test]
8483 fn test_simple_mpp() {
8484         // Simple test of sending a multi-path payment.
8485         let chanmon_cfgs = create_chanmon_cfgs(4);
8486         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8487         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8488         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8489
8490         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8491         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8492         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8493         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8494
8495         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8496         let path = route.paths[0].clone();
8497         route.paths.push(path);
8498         route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8499         route.paths[0][0].short_channel_id = chan_1_id;
8500         route.paths[0][1].short_channel_id = chan_3_id;
8501         route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8502         route.paths[1][0].short_channel_id = chan_2_id;
8503         route.paths[1][1].short_channel_id = chan_4_id;
8504         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8505         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8506 }
8507
8508 #[test]
8509 fn test_preimage_storage() {
8510         // Simple test of payment preimage storage allowing no client-side storage to claim payments
8511         let chanmon_cfgs = create_chanmon_cfgs(2);
8512         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8513         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8514         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8515
8516         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8517
8518         {
8519                 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200).unwrap();
8520                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8521                 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8522                 check_added_monitors!(nodes[0], 1);
8523                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8524                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8525                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8526                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8527         }
8528         // Note that after leaving the above scope we have no knowledge of any arguments or return
8529         // values from previous calls.
8530         expect_pending_htlcs_forwardable!(nodes[1]);
8531         let events = nodes[1].node.get_and_clear_pending_events();
8532         assert_eq!(events.len(), 1);
8533         match events[0] {
8534                 Event::PaymentReceived { ref purpose, .. } => {
8535                         match &purpose {
8536                                 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
8537                                         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8538                                 },
8539                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
8540                         }
8541                 },
8542                 _ => panic!("Unexpected event"),
8543         }
8544 }
8545
8546 #[test]
8547 #[allow(deprecated)]
8548 fn test_secret_timeout() {
8549         // Simple test of payment secret storage time outs. After
8550         // `create_inbound_payment(_for_hash)_legacy` is removed, this test will be removed as well.
8551         let chanmon_cfgs = create_chanmon_cfgs(2);
8552         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8553         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8554         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8555
8556         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8557
8558         let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment_legacy(Some(100_000), 2).unwrap();
8559
8560         // We should fail to register the same payment hash twice, at least until we've connected a
8561         // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
8562         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8563                 assert_eq!(err, "Duplicate payment hash");
8564         } else { panic!(); }
8565         let mut block = {
8566                 let node_1_blocks = nodes[1].blocks.lock().unwrap();
8567                 Block {
8568                         header: BlockHeader {
8569                                 version: 0x2000000,
8570                                 prev_blockhash: node_1_blocks.last().unwrap().0.block_hash(),
8571                                 merkle_root: Default::default(),
8572                                 time: node_1_blocks.len() as u32 + 7200, bits: 42, nonce: 42 },
8573                         txdata: vec![],
8574                 }
8575         };
8576         connect_block(&nodes[1], &block);
8577         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8578                 assert_eq!(err, "Duplicate payment hash");
8579         } else { panic!(); }
8580
8581         // If we then connect the second block, we should be able to register the same payment hash
8582         // again (this time getting a new payment secret).
8583         block.header.prev_blockhash = block.header.block_hash();
8584         block.header.time += 1;
8585         connect_block(&nodes[1], &block);
8586         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2).unwrap();
8587         assert_ne!(payment_secret_1, our_payment_secret);
8588
8589         {
8590                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8591                 nodes[0].node.send_payment(&route, payment_hash, &Some(our_payment_secret)).unwrap();
8592                 check_added_monitors!(nodes[0], 1);
8593                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8594                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8595                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8596                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8597         }
8598         // Note that after leaving the above scope we have no knowledge of any arguments or return
8599         // values from previous calls.
8600         expect_pending_htlcs_forwardable!(nodes[1]);
8601         let events = nodes[1].node.get_and_clear_pending_events();
8602         assert_eq!(events.len(), 1);
8603         match events[0] {
8604                 Event::PaymentReceived { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret }, .. } => {
8605                         assert!(payment_preimage.is_none());
8606                         assert_eq!(payment_secret, our_payment_secret);
8607                         // We don't actually have the payment preimage with which to claim this payment!
8608                 },
8609                 _ => panic!("Unexpected event"),
8610         }
8611 }
8612
8613 #[test]
8614 fn test_bad_secret_hash() {
8615         // Simple test of unregistered payment hash/invalid payment secret handling
8616         let chanmon_cfgs = create_chanmon_cfgs(2);
8617         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8618         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8619         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8620
8621         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8622
8623         let random_payment_hash = PaymentHash([42; 32]);
8624         let random_payment_secret = PaymentSecret([43; 32]);
8625         let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2).unwrap();
8626         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8627
8628         // All the below cases should end up being handled exactly identically, so we macro the
8629         // resulting events.
8630         macro_rules! handle_unknown_invalid_payment_data {
8631                 () => {
8632                         check_added_monitors!(nodes[0], 1);
8633                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8634                         let payment_event = SendEvent::from_event(events.pop().unwrap());
8635                         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8636                         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8637
8638                         // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8639                         // again to process the pending backwards-failure of the HTLC
8640                         expect_pending_htlcs_forwardable!(nodes[1]);
8641                         expect_pending_htlcs_forwardable!(nodes[1]);
8642                         check_added_monitors!(nodes[1], 1);
8643
8644                         // We should fail the payment back
8645                         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8646                         match events.pop().unwrap() {
8647                                 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8648                                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8649                                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8650                                 },
8651                                 _ => panic!("Unexpected event"),
8652                         }
8653                 }
8654         }
8655
8656         let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8657         // Error data is the HTLC value (100,000) and current block height
8658         let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8659
8660         // Send a payment with the right payment hash but the wrong payment secret
8661         nodes[0].node.send_payment(&route, our_payment_hash, &Some(random_payment_secret)).unwrap();
8662         handle_unknown_invalid_payment_data!();
8663         expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8664
8665         // Send a payment with a random payment hash, but the right payment secret
8666         nodes[0].node.send_payment(&route, random_payment_hash, &Some(our_payment_secret)).unwrap();
8667         handle_unknown_invalid_payment_data!();
8668         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8669
8670         // Send a payment with a random payment hash and random payment secret
8671         nodes[0].node.send_payment(&route, random_payment_hash, &Some(random_payment_secret)).unwrap();
8672         handle_unknown_invalid_payment_data!();
8673         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8674 }
8675
8676 #[test]
8677 fn test_update_err_monitor_lockdown() {
8678         // Our monitor will lock update of local commitment transaction if a broadcastion condition
8679         // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8680         // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
8681         //
8682         // This scenario may happen in a watchtower setup, where watchtower process a block height
8683         // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8684         // commitment at same time.
8685
8686         let chanmon_cfgs = create_chanmon_cfgs(2);
8687         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8688         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8689         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8690
8691         // Create some initial channel
8692         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8693         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8694
8695         // Rebalance the network to generate htlc in the two directions
8696         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8697
8698         // Route a HTLC from node 0 to node 1 (but don't settle)
8699         let preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8700
8701         // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8702         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8703         let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8704         let persister = test_utils::TestPersister::new();
8705         let watchtower = {
8706                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8707                 let mut w = test_utils::TestVecWriter(Vec::new());
8708                 monitor.write(&mut w).unwrap();
8709                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8710                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8711                 assert!(new_monitor == *monitor);
8712                 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);
8713                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8714                 watchtower
8715         };
8716         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8717         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8718         // transaction lock time requirements here.
8719         chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (header, 0));
8720         watchtower.chain_monitor.block_connected(&Block { header, txdata: vec![] }, 200);
8721
8722         // Try to update ChannelMonitor
8723         assert!(nodes[1].node.claim_funds(preimage));
8724         check_added_monitors!(nodes[1], 1);
8725         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8726         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8727         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8728         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8729                 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8730                         if let Err(_) =  watchtower.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8731                         if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8732                 } else { assert!(false); }
8733         } else { assert!(false); };
8734         // Our local monitor is in-sync and hasn't processed yet timeout
8735         check_added_monitors!(nodes[0], 1);
8736         let events = nodes[0].node.get_and_clear_pending_events();
8737         assert_eq!(events.len(), 1);
8738 }
8739
8740 #[test]
8741 fn test_concurrent_monitor_claim() {
8742         // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8743         // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8744         // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8745         // state N+1 confirms. Alice claims output from state N+1.
8746
8747         let chanmon_cfgs = create_chanmon_cfgs(2);
8748         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8749         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8750         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8751
8752         // Create some initial channel
8753         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8754         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8755
8756         // Rebalance the network to generate htlc in the two directions
8757         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8758
8759         // Route a HTLC from node 0 to node 1 (but don't settle)
8760         route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8761
8762         // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8763         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8764         let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8765         let persister = test_utils::TestPersister::new();
8766         let watchtower_alice = {
8767                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8768                 let mut w = test_utils::TestVecWriter(Vec::new());
8769                 monitor.write(&mut w).unwrap();
8770                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8771                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8772                 assert!(new_monitor == *monitor);
8773                 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);
8774                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8775                 watchtower
8776         };
8777         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8778         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8779         // transaction lock time requirements here.
8780         chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize((CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS) as usize, (header, 0));
8781         watchtower_alice.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8782
8783         // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8784         {
8785                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8786                 assert_eq!(txn.len(), 2);
8787                 txn.clear();
8788         }
8789
8790         // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8791         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8792         let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8793         let persister = test_utils::TestPersister::new();
8794         let watchtower_bob = {
8795                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8796                 let mut w = test_utils::TestVecWriter(Vec::new());
8797                 monitor.write(&mut w).unwrap();
8798                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8799                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8800                 assert!(new_monitor == *monitor);
8801                 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);
8802                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8803                 watchtower
8804         };
8805         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8806         watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8807
8808         // Route another payment to generate another update with still previous HTLC pending
8809         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8810         {
8811                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8812         }
8813         check_added_monitors!(nodes[1], 1);
8814
8815         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8816         assert_eq!(updates.update_add_htlcs.len(), 1);
8817         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8818         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8819                 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8820                         // Watchtower Alice should already have seen the block and reject the update
8821                         if let Err(_) =  watchtower_alice.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8822                         if let Ok(_) = watchtower_bob.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8823                         if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8824                 } else { assert!(false); }
8825         } else { assert!(false); };
8826         // Our local monitor is in-sync and hasn't processed yet timeout
8827         check_added_monitors!(nodes[0], 1);
8828
8829         //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8830         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8831         watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8832
8833         // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8834         let bob_state_y;
8835         {
8836                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8837                 assert_eq!(txn.len(), 2);
8838                 bob_state_y = txn[0].clone();
8839                 txn.clear();
8840         };
8841
8842         // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8843         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8844         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);
8845         {
8846                 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8847                 // We broadcast twice the transaction, once due to the HTLC-timeout, once due
8848                 // the onchain detection of the HTLC output
8849                 assert_eq!(htlc_txn.len(), 2);
8850                 check_spends!(htlc_txn[0], bob_state_y);
8851                 check_spends!(htlc_txn[1], bob_state_y);
8852         }
8853 }
8854
8855 #[test]
8856 fn test_pre_lockin_no_chan_closed_update() {
8857         // Test that if a peer closes a channel in response to a funding_created message we don't
8858         // generate a channel update (as the channel cannot appear on chain without a funding_signed
8859         // message).
8860         //
8861         // Doing so would imply a channel monitor update before the initial channel monitor
8862         // registration, violating our API guarantees.
8863         //
8864         // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8865         // then opening a second channel with the same funding output as the first (which is not
8866         // rejected because the first channel does not exist in the ChannelManager) and closing it
8867         // before receiving funding_signed.
8868         let chanmon_cfgs = create_chanmon_cfgs(2);
8869         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8870         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8871         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8872
8873         // Create an initial channel
8874         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8875         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8876         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8877         let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8878         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8879
8880         // Move the first channel through the funding flow...
8881         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8882
8883         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8884         check_added_monitors!(nodes[0], 0);
8885
8886         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8887         let channel_id = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8888         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8889         assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8890         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "Hi".to_string() }, true);
8891 }
8892
8893 #[test]
8894 fn test_htlc_no_detection() {
8895         // This test is a mutation to underscore the detection logic bug we had
8896         // before #653. HTLC value routed is above the remaining balance, thus
8897         // inverting HTLC and `to_remote` output. HTLC will come second and
8898         // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8899         // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8900         // outputs order detection for correct spending children filtring.
8901
8902         let chanmon_cfgs = create_chanmon_cfgs(2);
8903         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8904         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8905         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8906
8907         // Create some initial channels
8908         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8909
8910         send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8911         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8912         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8913         assert_eq!(local_txn[0].input.len(), 1);
8914         assert_eq!(local_txn[0].output.len(), 3);
8915         check_spends!(local_txn[0], chan_1.3);
8916
8917         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8918         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8919         connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] });
8920         // We deliberately connect the local tx twice as this should provoke a failure calling
8921         // this test before #653 fix.
8922         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);
8923         check_closed_broadcast!(nodes[0], true);
8924         check_added_monitors!(nodes[0], 1);
8925         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8926         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1);
8927
8928         let htlc_timeout = {
8929                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8930                 assert_eq!(node_txn[1].input.len(), 1);
8931                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8932                 check_spends!(node_txn[1], local_txn[0]);
8933                 node_txn[1].clone()
8934         };
8935
8936         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8937         connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] });
8938         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8939         expect_payment_failed!(nodes[0], our_payment_hash, true);
8940 }
8941
8942 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8943         // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8944         // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8945         // Carol, Alice would be the upstream node, and Carol the downstream.)
8946         //
8947         // Steps of the test:
8948         // 1) Alice sends a HTLC to Carol through Bob.
8949         // 2) Carol doesn't settle the HTLC.
8950         // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8951         // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8952         // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8953         //    but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8954         // 5) Carol release the preimage to Bob off-chain.
8955         // 6) Bob claims the offered output on the broadcasted commitment.
8956         let chanmon_cfgs = create_chanmon_cfgs(3);
8957         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8958         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8959         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8960
8961         // Create some initial channels
8962         let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8963         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8964
8965         // Steps (1) and (2):
8966         // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8967         let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3_000_000);
8968
8969         // Check that Alice's commitment transaction now contains an output for this HTLC.
8970         let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8971         check_spends!(alice_txn[0], chan_ab.3);
8972         assert_eq!(alice_txn[0].output.len(), 2);
8973         check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8974         assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8975         assert_eq!(alice_txn.len(), 2);
8976
8977         // Steps (3) and (4):
8978         // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8979         // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8980         let mut force_closing_node = 0; // Alice force-closes
8981         let mut counterparty_node = 1; // Bob if Alice force-closes
8982
8983         // Bob force-closes
8984         if !broadcast_alice {
8985                 force_closing_node = 1;
8986                 counterparty_node = 0;
8987         }
8988         nodes[force_closing_node].node.force_close_channel(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id()).unwrap();
8989         check_closed_broadcast!(nodes[force_closing_node], true);
8990         check_added_monitors!(nodes[force_closing_node], 1);
8991         check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
8992         if go_onchain_before_fulfill {
8993                 let txn_to_broadcast = match broadcast_alice {
8994                         true => alice_txn.clone(),
8995                         false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8996                 };
8997                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8998                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8999                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
9000                 if broadcast_alice {
9001                         check_closed_broadcast!(nodes[1], true);
9002                         check_added_monitors!(nodes[1], 1);
9003                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
9004                 }
9005                 assert_eq!(bob_txn.len(), 1);
9006                 check_spends!(bob_txn[0], chan_ab.3);
9007         }
9008
9009         // Step (5):
9010         // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
9011         // process of removing the HTLC from their commitment transactions.
9012         assert!(nodes[2].node.claim_funds(payment_preimage));
9013         check_added_monitors!(nodes[2], 1);
9014         let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
9015         assert!(carol_updates.update_add_htlcs.is_empty());
9016         assert!(carol_updates.update_fail_htlcs.is_empty());
9017         assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
9018         assert!(carol_updates.update_fee.is_none());
9019         assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
9020
9021         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
9022         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false, false);
9023         // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
9024         if !go_onchain_before_fulfill && broadcast_alice {
9025                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9026                 assert_eq!(events.len(), 1);
9027                 match events[0] {
9028                         MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
9029                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9030                         },
9031                         _ => panic!("Unexpected event"),
9032                 };
9033         }
9034         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
9035         // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
9036         // Carol<->Bob's updated commitment transaction info.
9037         check_added_monitors!(nodes[1], 2);
9038
9039         let events = nodes[1].node.get_and_clear_pending_msg_events();
9040         assert_eq!(events.len(), 2);
9041         let bob_revocation = match events[0] {
9042                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
9043                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
9044                         (*msg).clone()
9045                 },
9046                 _ => panic!("Unexpected event"),
9047         };
9048         let bob_updates = match events[1] {
9049                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
9050                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
9051                         (*updates).clone()
9052                 },
9053                 _ => panic!("Unexpected event"),
9054         };
9055
9056         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
9057         check_added_monitors!(nodes[2], 1);
9058         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
9059         check_added_monitors!(nodes[2], 1);
9060
9061         let events = nodes[2].node.get_and_clear_pending_msg_events();
9062         assert_eq!(events.len(), 1);
9063         let carol_revocation = match events[0] {
9064                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
9065                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
9066                         (*msg).clone()
9067                 },
9068                 _ => panic!("Unexpected event"),
9069         };
9070         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
9071         check_added_monitors!(nodes[1], 1);
9072
9073         // If this test requires the force-closed channel to not be on-chain until after the fulfill,
9074         // here's where we put said channel's commitment tx on-chain.
9075         let mut txn_to_broadcast = alice_txn.clone();
9076         if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
9077         if !go_onchain_before_fulfill {
9078                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
9079                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
9080                 // If Bob was the one to force-close, he will have already passed these checks earlier.
9081                 if broadcast_alice {
9082                         check_closed_broadcast!(nodes[1], true);
9083                         check_added_monitors!(nodes[1], 1);
9084                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
9085                 }
9086                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9087                 if broadcast_alice {
9088                         // In `connect_block()`, the ChainMonitor and ChannelManager are separately notified about a
9089                         // new block being connected. The ChannelManager being notified triggers a monitor update,
9090                         // which triggers broadcasting our commitment tx and an HTLC-claiming tx. The ChainMonitor
9091                         // being notified triggers the HTLC-claiming tx redundantly, resulting in 3 total txs being
9092                         // broadcasted.
9093                         assert_eq!(bob_txn.len(), 3);
9094                         check_spends!(bob_txn[1], chan_ab.3);
9095                 } else {
9096                         assert_eq!(bob_txn.len(), 2);
9097                         check_spends!(bob_txn[0], chan_ab.3);
9098                 }
9099         }
9100
9101         // Step (6):
9102         // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
9103         // broadcasted commitment transaction.
9104         {
9105                 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
9106                 if go_onchain_before_fulfill {
9107                         // Bob should now have an extra broadcasted tx, for the preimage-claiming transaction.
9108                         assert_eq!(bob_txn.len(), 2);
9109                 }
9110                 let script_weight = match broadcast_alice {
9111                         true => OFFERED_HTLC_SCRIPT_WEIGHT,
9112                         false => ACCEPTED_HTLC_SCRIPT_WEIGHT
9113                 };
9114                 // If Alice force-closed and Bob didn't receive her commitment transaction until after he
9115                 // received Carol's fulfill, he broadcasts the HTLC-output-claiming transaction first. Else if
9116                 // Bob force closed or if he found out about Alice's commitment tx before receiving Carol's
9117                 // fulfill, then he broadcasts the HTLC-output-claiming transaction second.
9118                 if broadcast_alice && !go_onchain_before_fulfill {
9119                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
9120                         assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
9121                 } else {
9122                         check_spends!(bob_txn[1], txn_to_broadcast[0]);
9123                         assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
9124                 }
9125         }
9126 }
9127
9128 #[test]
9129 fn test_onchain_htlc_settlement_after_close() {
9130         do_test_onchain_htlc_settlement_after_close(true, true);
9131         do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
9132         do_test_onchain_htlc_settlement_after_close(true, false);
9133         do_test_onchain_htlc_settlement_after_close(false, false);
9134 }
9135
9136 #[test]
9137 fn test_duplicate_chan_id() {
9138         // Test that if a given peer tries to open a channel with the same channel_id as one that is
9139         // already open we reject it and keep the old channel.
9140         //
9141         // Previously, full_stack_target managed to figure out that if you tried to open two channels
9142         // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
9143         // the existing channel when we detect the duplicate new channel, screwing up our monitor
9144         // updating logic for the existing channel.
9145         let chanmon_cfgs = create_chanmon_cfgs(2);
9146         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9147         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9148         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9149
9150         // Create an initial channel
9151         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9152         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9153         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9154         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()));
9155
9156         // Try to create a second channel with the same temporary_channel_id as the first and check
9157         // that it is rejected.
9158         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9159         {
9160                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9161                 assert_eq!(events.len(), 1);
9162                 match events[0] {
9163                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9164                                 // Technically, at this point, nodes[1] would be justified in thinking both the
9165                                 // first (valid) and second (invalid) channels are closed, given they both have
9166                                 // the same non-temporary channel_id. However, currently we do not, so we just
9167                                 // move forward with it.
9168                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9169                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9170                         },
9171                         _ => panic!("Unexpected event"),
9172                 }
9173         }
9174
9175         // Move the first channel through the funding flow...
9176         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
9177
9178         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9179         check_added_monitors!(nodes[0], 0);
9180
9181         let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9182         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
9183         {
9184                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
9185                 assert_eq!(added_monitors.len(), 1);
9186                 assert_eq!(added_monitors[0].0, funding_output);
9187                 added_monitors.clear();
9188         }
9189         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9190
9191         let funding_outpoint = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
9192         let channel_id = funding_outpoint.to_channel_id();
9193
9194         // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
9195         // temporary one).
9196
9197         // First try to open a second channel with a temporary channel id equal to the txid-based one.
9198         // Technically this is allowed by the spec, but we don't support it and there's little reason
9199         // to. Still, it shouldn't cause any other issues.
9200         open_chan_msg.temporary_channel_id = channel_id;
9201         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9202         {
9203                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9204                 assert_eq!(events.len(), 1);
9205                 match events[0] {
9206                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9207                                 // Technically, at this point, nodes[1] would be justified in thinking both
9208                                 // channels are closed, but currently we do not, so we just move forward with it.
9209                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9210                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9211                         },
9212                         _ => panic!("Unexpected event"),
9213                 }
9214         }
9215
9216         // Now try to create a second channel which has a duplicate funding output.
9217         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9218         let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9219         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_2_msg);
9220         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()));
9221         create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
9222
9223         let funding_created = {
9224                 let mut a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
9225                 let mut as_chan = a_channel_lock.by_id.get_mut(&open_chan_2_msg.temporary_channel_id).unwrap();
9226                 let logger = test_utils::TestLogger::new();
9227                 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
9228         };
9229         check_added_monitors!(nodes[0], 0);
9230         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
9231         // At this point we'll try to add a duplicate channel monitor, which will be rejected, but
9232         // still needs to be cleared here.
9233         check_added_monitors!(nodes[1], 1);
9234
9235         // ...still, nodes[1] will reject the duplicate channel.
9236         {
9237                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9238                 assert_eq!(events.len(), 1);
9239                 match events[0] {
9240                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9241                                 // Technically, at this point, nodes[1] would be justified in thinking both
9242                                 // channels are closed, but currently we do not, so we just move forward with it.
9243                                 assert_eq!(msg.channel_id, channel_id);
9244                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9245                         },
9246                         _ => panic!("Unexpected event"),
9247                 }
9248         }
9249
9250         // finally, finish creating the original channel and send a payment over it to make sure
9251         // everything is functional.
9252         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
9253         {
9254                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9255                 assert_eq!(added_monitors.len(), 1);
9256                 assert_eq!(added_monitors[0].0, funding_output);
9257                 added_monitors.clear();
9258         }
9259
9260         let events_4 = nodes[0].node.get_and_clear_pending_events();
9261         assert_eq!(events_4.len(), 0);
9262         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9263         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
9264
9265         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9266         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
9267         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9268         send_payment(&nodes[0], &[&nodes[1]], 8000000);
9269 }
9270
9271 #[test]
9272 fn test_error_chans_closed() {
9273         // Test that we properly handle error messages, closing appropriate channels.
9274         //
9275         // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
9276         // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
9277         // we can test various edge cases around it to ensure we don't regress.
9278         let chanmon_cfgs = create_chanmon_cfgs(3);
9279         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9280         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9281         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9282
9283         // Create some initial channels
9284         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9285         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9286         let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9287
9288         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9289         assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
9290         assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
9291
9292         // Closing a channel from a different peer has no effect
9293         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
9294         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9295
9296         // Closing one channel doesn't impact others
9297         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
9298         check_added_monitors!(nodes[0], 1);
9299         check_closed_broadcast!(nodes[0], false);
9300         check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
9301         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
9302         assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
9303         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);
9304         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);
9305
9306         // A null channel ID should close all channels
9307         let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9308         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
9309         check_added_monitors!(nodes[0], 2);
9310         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
9311         let events = nodes[0].node.get_and_clear_pending_msg_events();
9312         assert_eq!(events.len(), 2);
9313         match events[0] {
9314                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9315                         assert_eq!(msg.contents.flags & 2, 2);
9316                 },
9317                 _ => panic!("Unexpected event"),
9318         }
9319         match events[1] {
9320                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9321                         assert_eq!(msg.contents.flags & 2, 2);
9322                 },
9323                 _ => panic!("Unexpected event"),
9324         }
9325         // Note that at this point users of a standard PeerHandler will end up calling
9326         // peer_disconnected with no_connection_possible set to false, duplicating the
9327         // close-all-channels logic. That's OK, we don't want to end up not force-closing channels for
9328         // users with their own peer handling logic. We duplicate the call here, however.
9329         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9330         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9331
9332         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
9333         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9334         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9335 }
9336
9337 #[test]
9338 fn test_invalid_funding_tx() {
9339         // Test that we properly handle invalid funding transactions sent to us from a peer.
9340         //
9341         // Previously, all other major lightning implementations had failed to properly sanitize
9342         // funding transactions from their counterparties, leading to a multi-implementation critical
9343         // security vulnerability (though we always sanitized properly, we've previously had
9344         // un-released crashes in the sanitization process).
9345         let chanmon_cfgs = create_chanmon_cfgs(2);
9346         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9347         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9348         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9349
9350         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
9351         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()));
9352         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()));
9353
9354         let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
9355         for output in tx.output.iter_mut() {
9356                 // Make the confirmed funding transaction have a bogus script_pubkey
9357                 output.script_pubkey = bitcoin::Script::new();
9358         }
9359
9360         nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
9361         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()));
9362         check_added_monitors!(nodes[1], 1);
9363
9364         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()));
9365         check_added_monitors!(nodes[0], 1);
9366
9367         let events_1 = nodes[0].node.get_and_clear_pending_events();
9368         assert_eq!(events_1.len(), 0);
9369
9370         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9371         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9372         nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9373
9374         let expected_err = "funding tx had wrong script/value or output index";
9375         confirm_transaction_at(&nodes[1], &tx, 1);
9376         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
9377         check_added_monitors!(nodes[1], 1);
9378         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9379         assert_eq!(events_2.len(), 1);
9380         if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9381                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9382                 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
9383                         assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
9384                 } else { panic!(); }
9385         } else { panic!(); }
9386         assert_eq!(nodes[1].node.list_channels().len(), 0);
9387 }
9388
9389 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9390         // In the first version of the chain::Confirm interface, after a refactor was made to not
9391         // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9392         // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9393         // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9394         // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9395         // spending transaction until height N+1 (or greater). This was due to the way
9396         // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9397         // spending transaction at the height the input transaction was confirmed at, not whether we
9398         // should broadcast a spending transaction at the current height.
9399         // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9400         // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9401         // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9402         // until we learned about an additional block.
9403         //
9404         // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9405         // aren't broadcasting transactions too early (ie not broadcasting them at all).
9406         let chanmon_cfgs = create_chanmon_cfgs(3);
9407         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9408         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9409         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9410         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9411
9412         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
9413         let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
9414         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9415         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
9416         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9417
9418         nodes[1].node.force_close_channel(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
9419         check_closed_broadcast!(nodes[1], true);
9420         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
9421         check_added_monitors!(nodes[1], 1);
9422         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9423         assert_eq!(node_txn.len(), 1);
9424
9425         let conf_height = nodes[1].best_block_info().1;
9426         if !test_height_before_timelock {
9427                 connect_blocks(&nodes[1], 24 * 6);
9428         }
9429         nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9430                 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9431         if test_height_before_timelock {
9432                 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9433                 // generate any events or broadcast any transactions
9434                 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9435                 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9436         } else {
9437                 // We should broadcast an HTLC transaction spending our funding transaction first
9438                 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9439                 assert_eq!(spending_txn.len(), 2);
9440                 assert_eq!(spending_txn[0], node_txn[0]);
9441                 check_spends!(spending_txn[1], node_txn[0]);
9442                 // We should also generate a SpendableOutputs event with the to_self output (as its
9443                 // timelock is up).
9444                 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9445                 assert_eq!(descriptor_spend_txn.len(), 1);
9446
9447                 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9448                 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9449                 // additional block built on top of the current chain.
9450                 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9451                         &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9452                 expect_pending_htlcs_forwardable!(nodes[1]);
9453                 check_added_monitors!(nodes[1], 1);
9454
9455                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9456                 assert!(updates.update_add_htlcs.is_empty());
9457                 assert!(updates.update_fulfill_htlcs.is_empty());
9458                 assert_eq!(updates.update_fail_htlcs.len(), 1);
9459                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9460                 assert!(updates.update_fee.is_none());
9461                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9462                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9463                 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9464         }
9465 }
9466
9467 #[test]
9468 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9469         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9470         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9471 }
9472
9473 #[test]
9474 fn test_forwardable_regen() {
9475         // Tests that if we reload a ChannelManager while forwards are pending we will regenerate the
9476         // PendingHTLCsForwardable event automatically, ensuring we don't forget to forward/receive
9477         // HTLCs.
9478         // We test it for both payment receipt and payment forwarding.
9479
9480         let chanmon_cfgs = create_chanmon_cfgs(3);
9481         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9482         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9483         let persister: test_utils::TestPersister;
9484         let new_chain_monitor: test_utils::TestChainMonitor;
9485         let nodes_1_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
9486         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9487         let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
9488         let chan_id_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known()).2;
9489
9490         // First send a payment to nodes[1]
9491         let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
9492         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
9493         check_added_monitors!(nodes[0], 1);
9494
9495         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9496         assert_eq!(events.len(), 1);
9497         let payment_event = SendEvent::from_event(events.pop().unwrap());
9498         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9499         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9500
9501         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9502
9503         // Next send a payment which is forwarded by nodes[1]
9504         let (route_2, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 200_000);
9505         nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
9506         check_added_monitors!(nodes[0], 1);
9507
9508         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9509         assert_eq!(events.len(), 1);
9510         let payment_event = SendEvent::from_event(events.pop().unwrap());
9511         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9512         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9513
9514         // There is already a PendingHTLCsForwardable event "pending" so another one will not be
9515         // generated
9516         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
9517
9518         // Now restart nodes[1] and make sure it regenerates a single PendingHTLCsForwardable
9519         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9520         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9521
9522         let nodes_1_serialized = nodes[1].node.encode();
9523         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9524         let mut chan_1_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9525         get_monitor!(nodes[1], chan_id_1).write(&mut chan_0_monitor_serialized).unwrap();
9526         get_monitor!(nodes[1], chan_id_2).write(&mut chan_1_monitor_serialized).unwrap();
9527
9528         persister = test_utils::TestPersister::new();
9529         let keys_manager = &chanmon_cfgs[1].keys_manager;
9530         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);
9531         nodes[1].chain_monitor = &new_chain_monitor;
9532
9533         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
9534         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9535                 &mut chan_0_monitor_read, keys_manager).unwrap();
9536         assert!(chan_0_monitor_read.is_empty());
9537         let mut chan_1_monitor_read = &chan_1_monitor_serialized.0[..];
9538         let (_, mut chan_1_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9539                 &mut chan_1_monitor_read, keys_manager).unwrap();
9540         assert!(chan_1_monitor_read.is_empty());
9541
9542         let mut nodes_1_read = &nodes_1_serialized[..];
9543         let (_, nodes_1_deserialized_tmp) = {
9544                 let mut channel_monitors = HashMap::new();
9545                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
9546                 channel_monitors.insert(chan_1_monitor.get_funding_txo().0, &mut chan_1_monitor);
9547                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_1_read, ChannelManagerReadArgs {
9548                         default_config: UserConfig::default(),
9549                         keys_manager,
9550                         fee_estimator: node_cfgs[1].fee_estimator,
9551                         chain_monitor: nodes[1].chain_monitor,
9552                         tx_broadcaster: nodes[1].tx_broadcaster.clone(),
9553                         logger: nodes[1].logger,
9554                         channel_monitors,
9555                 }).unwrap()
9556         };
9557         nodes_1_deserialized = nodes_1_deserialized_tmp;
9558         assert!(nodes_1_read.is_empty());
9559
9560         assert!(nodes[1].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
9561         assert!(nodes[1].chain_monitor.watch_channel(chan_1_monitor.get_funding_txo().0, chan_1_monitor).is_ok());
9562         nodes[1].node = &nodes_1_deserialized;
9563         check_added_monitors!(nodes[1], 2);
9564
9565         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9566         // Note that nodes[1] and nodes[2] resend their funding_locked here since they haven't updated
9567         // the commitment state.
9568         reconnect_nodes(&nodes[1], &nodes[2], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9569
9570         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
9571
9572         expect_pending_htlcs_forwardable!(nodes[1]);
9573         expect_payment_received!(nodes[1], payment_hash, payment_secret, 100_000);
9574         check_added_monitors!(nodes[1], 1);
9575
9576         let mut events = nodes[1].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[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9580         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false);
9581         expect_pending_htlcs_forwardable!(nodes[2]);
9582         expect_payment_received!(nodes[2], payment_hash_2, payment_secret_2, 200_000);
9583
9584         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
9585         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage_2);
9586 }
9587
9588 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
9589         let chanmon_cfgs = create_chanmon_cfgs(2);
9590         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9591         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9592         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9593
9594         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9595
9596         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
9597                 .with_features(InvoiceFeatures::known());
9598         let route = get_route!(nodes[0], payment_params, 10_000, TEST_FINAL_CLTV).unwrap();
9599
9600         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9601
9602         {
9603                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
9604                 check_added_monitors!(nodes[0], 1);
9605                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9606                 assert_eq!(events.len(), 1);
9607                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9608                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9609                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9610         }
9611         expect_pending_htlcs_forwardable!(nodes[1]);
9612         expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9613
9614         {
9615                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
9616                 check_added_monitors!(nodes[0], 1);
9617                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9618                 assert_eq!(events.len(), 1);
9619                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9620                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9621                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9622                 // At this point, nodes[1] would notice it has too much value for the payment. It will
9623                 // assume the second is a privacy attack (no longer particularly relevant
9624                 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9625                 // the first HTLC delivered above.
9626         }
9627
9628         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9629         nodes[1].node.process_pending_htlc_forwards();
9630
9631         if test_for_second_fail_panic {
9632                 // Now we go fail back the first HTLC from the user end.
9633                 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9634
9635                 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9636                 nodes[1].node.process_pending_htlc_forwards();
9637
9638                 check_added_monitors!(nodes[1], 1);
9639                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9640                 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9641
9642                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9643                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9644                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9645
9646                 let failure_events = nodes[0].node.get_and_clear_pending_events();
9647                 assert_eq!(failure_events.len(), 2);
9648                 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9649                 if let Event::PaymentPathFailed { .. } = failure_events[1] {} else { panic!(); }
9650         } else {
9651                 // Let the second HTLC fail and claim the first
9652                 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9653                 nodes[1].node.process_pending_htlc_forwards();
9654
9655                 check_added_monitors!(nodes[1], 1);
9656                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9657                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9658                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9659
9660                 expect_payment_failed_conditions!(nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9661
9662                 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9663         }
9664 }
9665
9666 #[test]
9667 fn test_dup_htlc_second_fail_panic() {
9668         // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9669         // value for the payment, we'd fail back both HTLCs after generating a `PaymentReceived` event.
9670         // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9671         // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9672         do_test_dup_htlc_second_rejected(true);
9673 }
9674
9675 #[test]
9676 fn test_dup_htlc_second_rejected() {
9677         // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9678         // simply reject the second HTLC but are still able to claim the first HTLC.
9679         do_test_dup_htlc_second_rejected(false);
9680 }
9681
9682 #[test]
9683 fn test_inconsistent_mpp_params() {
9684         // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9685         // such HTLC and allow the second to stay.
9686         let chanmon_cfgs = create_chanmon_cfgs(4);
9687         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9688         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9689         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9690
9691         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9692         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9693         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9694         create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9695
9696         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id())
9697                 .with_features(InvoiceFeatures::known());
9698         let mut route = get_route!(nodes[0], payment_params, 15_000_000, TEST_FINAL_CLTV).unwrap();
9699         assert_eq!(route.paths.len(), 2);
9700         route.paths.sort_by(|path_a, _| {
9701                 // Sort the path so that the path through nodes[1] comes first
9702                 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
9703                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9704         });
9705         let payment_params_opt = Some(payment_params);
9706
9707         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9708
9709         let cur_height = nodes[0].best_block_info().1;
9710         let payment_id = PaymentId([42; 32]);
9711         {
9712                 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();
9713                 check_added_monitors!(nodes[0], 1);
9714
9715                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9716                 assert_eq!(events.len(), 1);
9717                 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9718         }
9719         assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9720
9721         {
9722                 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();
9723                 check_added_monitors!(nodes[0], 1);
9724
9725                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9726                 assert_eq!(events.len(), 1);
9727                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9728
9729                 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9730                 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9731
9732                 expect_pending_htlcs_forwardable!(nodes[2]);
9733                 check_added_monitors!(nodes[2], 1);
9734
9735                 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9736                 assert_eq!(events.len(), 1);
9737                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9738
9739                 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9740                 check_added_monitors!(nodes[3], 0);
9741                 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9742
9743                 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9744                 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9745                 // post-payment_secrets) and fail back the new HTLC.
9746         }
9747         expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9748         nodes[3].node.process_pending_htlc_forwards();
9749         expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9750         nodes[3].node.process_pending_htlc_forwards();
9751
9752         check_added_monitors!(nodes[3], 1);
9753
9754         let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9755         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9756         commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9757
9758         expect_pending_htlcs_forwardable!(nodes[2]);
9759         check_added_monitors!(nodes[2], 1);
9760
9761         let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9762         nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9763         commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9764
9765         expect_payment_failed_conditions!(nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9766
9767         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();
9768         check_added_monitors!(nodes[0], 1);
9769
9770         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9771         assert_eq!(events.len(), 1);
9772         pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9773
9774         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9775 }
9776
9777 #[test]
9778 fn test_keysend_payments_to_public_node() {
9779         let chanmon_cfgs = create_chanmon_cfgs(2);
9780         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9781         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9782         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9783
9784         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9785         let network_graph = nodes[0].network_graph;
9786         let payer_pubkey = nodes[0].node.get_our_node_id();
9787         let payee_pubkey = nodes[1].node.get_our_node_id();
9788         let route_params = RouteParameters {
9789                 payment_params: PaymentParameters::for_keysend(payee_pubkey),
9790                 final_value_msat: 10000,
9791                 final_cltv_expiry_delta: 40,
9792         };
9793         let scorer = test_utils::TestScorer::with_penalty(0);
9794         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9795         let route = find_route(&payer_pubkey, &route_params, network_graph, None, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
9796
9797         let test_preimage = PaymentPreimage([42; 32]);
9798         let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9799         check_added_monitors!(nodes[0], 1);
9800         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9801         assert_eq!(events.len(), 1);
9802         let event = events.pop().unwrap();
9803         let path = vec![&nodes[1]];
9804         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9805         claim_payment(&nodes[0], &path, test_preimage);
9806 }
9807
9808 #[test]
9809 fn test_keysend_payments_to_private_node() {
9810         let chanmon_cfgs = create_chanmon_cfgs(2);
9811         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9812         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9813         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9814
9815         let payer_pubkey = nodes[0].node.get_our_node_id();
9816         let payee_pubkey = nodes[1].node.get_our_node_id();
9817         nodes[0].node.peer_connected(&payee_pubkey, &msgs::Init { features: InitFeatures::known(), remote_network_address: None });
9818         nodes[1].node.peer_connected(&payer_pubkey, &msgs::Init { features: InitFeatures::known(), remote_network_address: None });
9819
9820         let _chan = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
9821         let route_params = RouteParameters {
9822                 payment_params: PaymentParameters::for_keysend(payee_pubkey),
9823                 final_value_msat: 10000,
9824                 final_cltv_expiry_delta: 40,
9825         };
9826         let network_graph = nodes[0].network_graph;
9827         let first_hops = nodes[0].node.list_usable_channels();
9828         let scorer = test_utils::TestScorer::with_penalty(0);
9829         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9830         let route = find_route(
9831                 &payer_pubkey, &route_params, network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
9832                 nodes[0].logger, &scorer, &random_seed_bytes
9833         ).unwrap();
9834
9835         let test_preimage = PaymentPreimage([42; 32]);
9836         let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9837         check_added_monitors!(nodes[0], 1);
9838         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9839         assert_eq!(events.len(), 1);
9840         let event = events.pop().unwrap();
9841         let path = vec![&nodes[1]];
9842         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9843         claim_payment(&nodes[0], &path, test_preimage);
9844 }
9845
9846 fn do_test_partial_claim_before_restart(persist_both_monitors: bool) {
9847         // Test what happens if a node receives an MPP payment, claims it, but crashes before
9848         // persisting the ChannelManager. If `persist_both_monitors` is false, also crash after only
9849         // updating one of the two channels' ChannelMonitors. As a result, on startup, we'll (a) still
9850         // have the PaymentReceived event, (b) have one (or two) channel(s) that goes on chain with the
9851         // HTLC preimage in them, and (c) optionally have one channel that is live off-chain but does
9852         // not have the preimage tied to the still-pending HTLC.
9853         //
9854         // To get to the correct state, on startup we should propagate the preimage to the
9855         // still-off-chain channel, claiming the HTLC as soon as the peer connects, with the monitor
9856         // receiving the preimage without a state update.
9857         let chanmon_cfgs = create_chanmon_cfgs(4);
9858         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9859         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9860
9861         let persister: test_utils::TestPersister;
9862         let new_chain_monitor: test_utils::TestChainMonitor;
9863         let nodes_3_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
9864
9865         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9866
9867         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9868         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9869         let chan_id_persisted = create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known()).2;
9870         let chan_id_not_persisted = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known()).2;
9871
9872         // Create an MPP route for 15k sats, more than the default htlc-max of 10%
9873         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
9874         assert_eq!(route.paths.len(), 2);
9875         route.paths.sort_by(|path_a, _| {
9876                 // Sort the path so that the path through nodes[1] comes first
9877                 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
9878                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9879         });
9880
9881         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
9882         check_added_monitors!(nodes[0], 2);
9883
9884         // Send the payment through to nodes[3] *without* clearing the PaymentReceived event
9885         let mut send_events = nodes[0].node.get_and_clear_pending_msg_events();
9886         assert_eq!(send_events.len(), 2);
9887         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);
9888         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);
9889
9890         // Now that we have an MPP payment pending, get the latest encoded copies of nodes[3]'s
9891         // monitors and ChannelManager, for use later, if we don't want to persist both monitors.
9892         let mut original_monitor = test_utils::TestVecWriter(Vec::new());
9893         if !persist_both_monitors {
9894                 for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
9895                         if outpoint.to_channel_id() == chan_id_not_persisted {
9896                                 assert!(original_monitor.0.is_empty());
9897                                 nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut original_monitor).unwrap();
9898                         }
9899                 }
9900         }
9901
9902         let mut original_manager = test_utils::TestVecWriter(Vec::new());
9903         nodes[3].node.write(&mut original_manager).unwrap();
9904
9905         expect_payment_received!(nodes[3], payment_hash, payment_secret, 15_000_000);
9906
9907         nodes[3].node.claim_funds(payment_preimage);
9908         check_added_monitors!(nodes[3], 2);
9909
9910         // Now fetch one of the two updated ChannelMonitors from nodes[3], and restart pretending we
9911         // crashed in between the two persistence calls - using one old ChannelMonitor and one new one,
9912         // with the old ChannelManager.
9913         let mut updated_monitor = test_utils::TestVecWriter(Vec::new());
9914         for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
9915                 if outpoint.to_channel_id() == chan_id_persisted {
9916                         assert!(updated_monitor.0.is_empty());
9917                         nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut updated_monitor).unwrap();
9918                 }
9919         }
9920         // If `persist_both_monitors` is set, get the second monitor here as well
9921         if persist_both_monitors {
9922                 for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
9923                         if outpoint.to_channel_id() == chan_id_not_persisted {
9924                                 assert!(original_monitor.0.is_empty());
9925                                 nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut original_monitor).unwrap();
9926                         }
9927                 }
9928         }
9929
9930         // Now restart nodes[3].
9931         persister = test_utils::TestPersister::new();
9932         let keys_manager = &chanmon_cfgs[3].keys_manager;
9933         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);
9934         nodes[3].chain_monitor = &new_chain_monitor;
9935         let mut monitors = Vec::new();
9936         for mut monitor_data in [original_monitor, updated_monitor].iter() {
9937                 let (_, mut deserialized_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut &monitor_data.0[..], keys_manager).unwrap();
9938                 monitors.push(deserialized_monitor);
9939         }
9940
9941         let config = UserConfig::default();
9942         nodes_3_deserialized = {
9943                 let mut channel_monitors = HashMap::new();
9944                 for monitor in monitors.iter_mut() {
9945                         channel_monitors.insert(monitor.get_funding_txo().0, monitor);
9946                 }
9947                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut &original_manager.0[..], ChannelManagerReadArgs {
9948                         default_config: config,
9949                         keys_manager,
9950                         fee_estimator: node_cfgs[3].fee_estimator,
9951                         chain_monitor: nodes[3].chain_monitor,
9952                         tx_broadcaster: nodes[3].tx_broadcaster.clone(),
9953                         logger: nodes[3].logger,
9954                         channel_monitors,
9955                 }).unwrap().1
9956         };
9957         nodes[3].node = &nodes_3_deserialized;
9958
9959         for monitor in monitors {
9960                 // On startup the preimage should have been copied into the non-persisted monitor:
9961                 assert!(monitor.get_stored_preimages().contains_key(&payment_hash));
9962                 nodes[3].chain_monitor.watch_channel(monitor.get_funding_txo().0.clone(), monitor).unwrap();
9963         }
9964         check_added_monitors!(nodes[3], 2);
9965
9966         nodes[1].node.peer_disconnected(&nodes[3].node.get_our_node_id(), false);
9967         nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), false);
9968
9969         // During deserialization, we should have closed one channel and broadcast its latest
9970         // commitment transaction. We should also still have the original PaymentReceived event we
9971         // never finished processing.
9972         let events = nodes[3].node.get_and_clear_pending_events();
9973         assert_eq!(events.len(), if persist_both_monitors { 3 } else { 2 });
9974         if let Event::PaymentReceived { amt: 15_000_000, .. } = events[0] { } else { panic!(); }
9975         if let Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } = events[1] { } else { panic!(); }
9976         if persist_both_monitors {
9977                 if let Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } = events[2] { } else { panic!(); }
9978         }
9979
9980         assert_eq!(nodes[3].node.list_channels().len(), if persist_both_monitors { 0 } else { 1 });
9981         if !persist_both_monitors {
9982                 // If one of the two channels is still live, reveal the payment preimage over it.
9983
9984                 nodes[3].node.peer_connected(&nodes[2].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
9985                 let reestablish_1 = get_chan_reestablish_msgs!(nodes[3], nodes[2]);
9986                 nodes[2].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
9987                 let reestablish_2 = get_chan_reestablish_msgs!(nodes[2], nodes[3]);
9988
9989                 nodes[2].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish_1[0]);
9990                 get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, nodes[3].node.get_our_node_id());
9991                 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
9992
9993                 nodes[3].node.handle_channel_reestablish(&nodes[2].node.get_our_node_id(), &reestablish_2[0]);
9994
9995                 // Once we call `get_and_clear_pending_msg_events` the holding cell is cleared and the HTLC
9996                 // claim should fly.
9997                 let ds_msgs = nodes[3].node.get_and_clear_pending_msg_events();
9998                 check_added_monitors!(nodes[3], 1);
9999                 assert_eq!(ds_msgs.len(), 2);
10000                 if let MessageSendEvent::SendChannelUpdate { .. } = ds_msgs[1] {} else { panic!(); }
10001
10002                 let cs_updates = match ds_msgs[0] {
10003                         MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
10004                                 nodes[2].node.handle_update_fulfill_htlc(&nodes[3].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
10005                                 check_added_monitors!(nodes[2], 1);
10006                                 let cs_updates = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
10007                                 expect_payment_forwarded!(nodes[2], nodes[0], nodes[3], Some(1000), false, false);
10008                                 commitment_signed_dance!(nodes[2], nodes[3], updates.commitment_signed, false, true);
10009                                 cs_updates
10010                         }
10011                         _ => panic!(),
10012                 };
10013
10014                 nodes[0].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &cs_updates.update_fulfill_htlcs[0]);
10015                 commitment_signed_dance!(nodes[0], nodes[2], cs_updates.commitment_signed, false, true);
10016                 expect_payment_sent!(nodes[0], payment_preimage);
10017         }
10018 }
10019
10020 #[test]
10021 fn test_partial_claim_before_restart() {
10022         do_test_partial_claim_before_restart(false);
10023         do_test_partial_claim_before_restart(true);
10024 }
10025
10026 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
10027 #[derive(Clone, Copy, PartialEq)]
10028 enum ExposureEvent {
10029         /// Breach occurs at HTLC forwarding (see `send_htlc`)
10030         AtHTLCForward,
10031         /// Breach occurs at HTLC reception (see `update_add_htlc`)
10032         AtHTLCReception,
10033         /// Breach occurs at outbound update_fee (see `send_update_fee`)
10034         AtUpdateFeeOutbound,
10035 }
10036
10037 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool) {
10038         // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
10039         // policy.
10040         //
10041         // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
10042         // trimmed-to-dust HTLC outbound balance and this new payment as included on next
10043         // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
10044         // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
10045         // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
10046         // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
10047         // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
10048         // might be available again for HTLC processing once the dust bandwidth has cleared up.
10049
10050         let chanmon_cfgs = create_chanmon_cfgs(2);
10051         let mut config = test_default_channel_config();
10052         config.channel_options.max_dust_htlc_exposure_msat = 5_000_000; // default setting value
10053         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10054         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
10055         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10056
10057         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
10058         let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10059         open_channel.max_htlc_value_in_flight_msat = 50_000_000;
10060         open_channel.max_accepted_htlcs = 60;
10061         if on_holder_tx {
10062                 open_channel.dust_limit_satoshis = 546;
10063         }
10064         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
10065         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10066         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
10067
10068         let opt_anchors = false;
10069
10070         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
10071
10072         if on_holder_tx {
10073                 if let Some(mut chan) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&temporary_channel_id) {
10074                         chan.holder_dust_limit_satoshis = 546;
10075                 }
10076         }
10077
10078         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
10079         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()));
10080         check_added_monitors!(nodes[1], 1);
10081
10082         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()));
10083         check_added_monitors!(nodes[0], 1);
10084
10085         let (funding_locked, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
10086         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
10087         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
10088
10089         let dust_buffer_feerate = {
10090                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
10091                 let chan = chan_lock.by_id.get(&channel_id).unwrap();
10092                 chan.get_dust_buffer_feerate(None) as u64
10093         };
10094         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;
10095         let dust_outbound_htlc_on_holder_tx: u64 = config.channel_options.max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
10096
10097         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;
10098         let dust_inbound_htlc_on_holder_tx: u64 = config.channel_options.max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
10099
10100         let dust_htlc_on_counterparty_tx: u64 = 25;
10101         let dust_htlc_on_counterparty_tx_msat: u64 = config.channel_options.max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
10102
10103         if on_holder_tx {
10104                 if dust_outbound_balance {
10105                         // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
10106                         // Outbound dust balance: 4372 sats
10107                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
10108                         for i in 0..dust_outbound_htlc_on_holder_tx {
10109                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
10110                                 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at dust HTLC {}", i); }
10111                         }
10112                 } else {
10113                         // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
10114                         // Inbound dust balance: 4372 sats
10115                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
10116                         for _ in 0..dust_inbound_htlc_on_holder_tx {
10117                                 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
10118                         }
10119                 }
10120         } else {
10121                 if dust_outbound_balance {
10122                         // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
10123                         // Outbound dust balance: 5000 sats
10124                         for i in 0..dust_htlc_on_counterparty_tx {
10125                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
10126                                 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at dust HTLC {}", i); }
10127                         }
10128                 } else {
10129                         // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
10130                         // Inbound dust balance: 5000 sats
10131                         for _ in 0..dust_htlc_on_counterparty_tx {
10132                                 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
10133                         }
10134                 }
10135         }
10136
10137         let dust_overflow = dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx + 1);
10138         if exposure_breach_event == ExposureEvent::AtHTLCForward {
10139                 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 });
10140                 let mut config = UserConfig::default();
10141                 // With default dust exposure: 5000 sats
10142                 if on_holder_tx {
10143                         let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * (dust_outbound_htlc_on_holder_tx + 1);
10144                         let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * dust_inbound_htlc_on_holder_tx + dust_outbound_htlc_on_holder_tx_msat;
10145                         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)));
10146                 } else {
10147                         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)));
10148                 }
10149         } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
10150                 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 });
10151                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
10152                 check_added_monitors!(nodes[1], 1);
10153                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
10154                 assert_eq!(events.len(), 1);
10155                 let payment_event = SendEvent::from_event(events.remove(0));
10156                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
10157                 // With default dust exposure: 5000 sats
10158                 if on_holder_tx {
10159                         // Outbound dust balance: 6399 sats
10160                         let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
10161                         let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
10162                         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);
10163                 } else {
10164                         // Outbound dust balance: 5200 sats
10165                         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);
10166                 }
10167         } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
10168                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 2_500_000);
10169                 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at update_fee-swallowed HTLC", ); }
10170                 {
10171                         let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
10172                         *feerate_lock = *feerate_lock * 10;
10173                 }
10174                 nodes[0].node.timer_tick_occurred();
10175                 check_added_monitors!(nodes[0], 1);
10176                 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);
10177         }
10178
10179         let _ = nodes[0].node.get_and_clear_pending_msg_events();
10180         let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
10181         added_monitors.clear();
10182 }
10183
10184 #[test]
10185 fn test_max_dust_htlc_exposure() {
10186         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true);
10187         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true);
10188         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true);
10189         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false);
10190         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false);
10191         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false);
10192         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true);
10193         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false);
10194         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true);
10195         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false);
10196         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false);
10197         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true);
10198 }