]> git.bitcoin.ninja Git - rust-lightning/blob - lightning/src/ln/functional_tests.rs
Merge pull request #1460 from TheBlueMatt/2022-04-liquidity-log
[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, 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::key::{PublicKey,SecretKey};
46
47 use regex;
48
49 use io;
50 use prelude::*;
51 use alloc::collections::BTreeSet;
52 use core::default::Default;
53 use sync::{Arc, Mutex};
54
55 use ln::functional_test_utils::*;
56 use ln::chan_utils::CommitmentTransaction;
57
58 #[test]
59 fn test_insane_channel_opens() {
60         // Stand up a network of 2 nodes
61         use ln::channel::TOTAL_BITCOIN_SUPPLY_SATOSHIS;
62         let mut cfg = UserConfig::default();
63         cfg.peer_channel_config_limits.max_funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1;
64         let chanmon_cfgs = create_chanmon_cfgs(2);
65         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
66         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(cfg)]);
67         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
68
69         // Instantiate channel parameters where we push the maximum msats given our
70         // funding satoshis
71         let channel_value_sat = 31337; // same as funding satoshis
72         let channel_reserve_satoshis = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value_sat);
73         let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
74
75         // Have node0 initiate a channel to node1 with aforementioned parameters
76         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
77
78         // Extract the channel open message from node0 to node1
79         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
80
81         // Test helper that asserts we get the correct error string given a mutator
82         // that supposedly makes the channel open message insane
83         let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
84                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &message_mutator(open_channel_message.clone()));
85                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
86                 assert_eq!(msg_events.len(), 1);
87                 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
88                 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
89                         match action {
90                                 &ErrorAction::SendErrorMessage { .. } => {
91                                         nodes[1].logger.assert_log_regex("lightning::ln::channelmanager".to_string(), expected_regex, 1);
92                                 },
93                                 _ => panic!("unexpected event!"),
94                         }
95                 } else { assert!(false); }
96         };
97
98         use ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
99
100         // Test all mutations that would make the channel open message insane
101         insane_open_helper(format!("Per our config, funding must be at most {}. It was {}", TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1, TOTAL_BITCOIN_SUPPLY_SATOSHIS + 2).as_str(), |mut msg| { msg.funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 2; msg });
102         insane_open_helper(format!("Funding must be smaller than the total bitcoin supply. It was {}", TOTAL_BITCOIN_SUPPLY_SATOSHIS).as_str(), |mut msg| { msg.funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS; msg });
103
104         insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
105
106         insane_open_helper(r"push_msat \d+ was larger than channel amount minus reserve \(\d+\)", |mut msg| { msg.push_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000 + 1; msg });
107
108         insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
109
110         insane_open_helper(r"Minimum htlc value \(\d+\) was larger than full channel value \(\d+\)", |mut msg| { msg.htlc_minimum_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000; msg });
111
112         insane_open_helper("They wanted our payments to be delayed by a needlessly long period", |mut msg| { msg.to_self_delay = MAX_LOCAL_BREAKDOWN_TIMEOUT + 1; msg });
113
114         insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
115
116         insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
117 }
118
119 #[test]
120 fn test_funding_exceeds_no_wumbo_limit() {
121         // Test that if a peer does not support wumbo channels, we'll refuse to open a wumbo channel to
122         // them.
123         use ln::channel::MAX_FUNDING_SATOSHIS_NO_WUMBO;
124         let chanmon_cfgs = create_chanmon_cfgs(2);
125         let mut node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
126         node_cfgs[1].features = InitFeatures::known().clear_wumbo();
127         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
128         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
129
130         match nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), MAX_FUNDING_SATOSHIS_NO_WUMBO + 1, 0, 42, None) {
131                 Err(APIError::APIMisuseError { err }) => {
132                         assert_eq!(format!("funding_value must not exceed {}, it was {}", MAX_FUNDING_SATOSHIS_NO_WUMBO, MAX_FUNDING_SATOSHIS_NO_WUMBO + 1), err);
133                 },
134                 _ => panic!()
135         }
136 }
137
138 fn do_test_counterparty_no_reserve(send_from_initiator: bool) {
139         // A peer providing a channel_reserve_satoshis of 0 (or less than our dust limit) is insecure,
140         // but only for them. Because some LSPs do it with some level of trust of the clients (for a
141         // substantial UX improvement), we explicitly allow it. Because it's unlikely to happen often
142         // in normal testing, we test it explicitly here.
143         let chanmon_cfgs = create_chanmon_cfgs(2);
144         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
145         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
146         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
147
148         // Have node0 initiate a channel to node1 with aforementioned parameters
149         let mut push_amt = 100_000_000;
150         let feerate_per_kw = 253;
151         let opt_anchors = false;
152         push_amt -= feerate_per_kw as u64 * (commitment_tx_base_weight(opt_anchors) + 4 * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000 * 1000;
153         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
154
155         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, if send_from_initiator { 0 } else { push_amt }, 42, None).unwrap();
156         let mut open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
157         if !send_from_initiator {
158                 open_channel_message.channel_reserve_satoshis = 0;
159                 open_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
160         }
161         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel_message);
162
163         // Extract the channel accept message from node1 to node0
164         let mut accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
165         if send_from_initiator {
166                 accept_channel_message.channel_reserve_satoshis = 0;
167                 accept_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
168         }
169         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel_message);
170         {
171                 let mut lock;
172                 let mut chan = get_channel_ref!(if send_from_initiator { &nodes[1] } else { &nodes[0] }, lock, temp_channel_id);
173                 chan.holder_selected_channel_reserve_satoshis = 0;
174                 chan.holder_max_htlc_value_in_flight_msat = 100_000_000;
175         }
176
177         let funding_tx = sign_funding_transaction(&nodes[0], &nodes[1], 100_000, temp_channel_id);
178         let funding_msgs = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &funding_tx);
179         create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_msgs.0);
180
181         // nodes[0] should now be able to send the full balance to nodes[1], violating nodes[1]'s
182         // security model if it ever tries to send funds back to nodes[0] (but that's not our problem).
183         if send_from_initiator {
184                 send_payment(&nodes[0], &[&nodes[1]], 100_000_000
185                         // Note that for outbound channels we have to consider the commitment tx fee and the
186                         // "fee spike buffer", which is currently a multiple of the total commitment tx fee as
187                         // well as an additional HTLC.
188                         - FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE * commit_tx_fee_msat(feerate_per_kw, 2, opt_anchors));
189         } else {
190                 send_payment(&nodes[1], &[&nodes[0]], push_amt);
191         }
192 }
193
194 #[test]
195 fn test_counterparty_no_reserve() {
196         do_test_counterparty_no_reserve(true);
197         do_test_counterparty_no_reserve(false);
198 }
199
200 #[test]
201 fn test_async_inbound_update_fee() {
202         let chanmon_cfgs = create_chanmon_cfgs(2);
203         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
204         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
205         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
206         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
207
208         // balancing
209         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
210
211         // A                                        B
212         // update_fee                            ->
213         // send (1) commitment_signed            -.
214         //                                       <- update_add_htlc/commitment_signed
215         // send (2) RAA (awaiting remote revoke) -.
216         // (1) commitment_signed is delivered    ->
217         //                                       .- send (3) RAA (awaiting remote revoke)
218         // (2) RAA is delivered                  ->
219         //                                       .- send (4) commitment_signed
220         //                                       <- (3) RAA is delivered
221         // send (5) commitment_signed            -.
222         //                                       <- (4) commitment_signed is delivered
223         // send (6) RAA                          -.
224         // (5) commitment_signed is delivered    ->
225         //                                       <- RAA
226         // (6) RAA is delivered                  ->
227
228         // First nodes[0] generates an update_fee
229         {
230                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
231                 *feerate_lock += 20;
232         }
233         nodes[0].node.timer_tick_occurred();
234         check_added_monitors!(nodes[0], 1);
235
236         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
237         assert_eq!(events_0.len(), 1);
238         let (update_msg, commitment_signed) = match events_0[0] { // (1)
239                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
240                         (update_fee.as_ref(), commitment_signed)
241                 },
242                 _ => panic!("Unexpected event"),
243         };
244
245         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
246
247         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
248         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
249         nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
250         check_added_monitors!(nodes[1], 1);
251
252         let payment_event = {
253                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
254                 assert_eq!(events_1.len(), 1);
255                 SendEvent::from_event(events_1.remove(0))
256         };
257         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
258         assert_eq!(payment_event.msgs.len(), 1);
259
260         // ...now when the messages get delivered everyone should be happy
261         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
262         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
263         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
264         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
265         check_added_monitors!(nodes[0], 1);
266
267         // deliver(1), generate (3):
268         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
269         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
270         // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
271         check_added_monitors!(nodes[1], 1);
272
273         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
274         let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
275         assert!(bs_update.update_add_htlcs.is_empty()); // (4)
276         assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
277         assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
278         assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
279         assert!(bs_update.update_fee.is_none()); // (4)
280         check_added_monitors!(nodes[1], 1);
281
282         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
283         let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
284         assert!(as_update.update_add_htlcs.is_empty()); // (5)
285         assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
286         assert!(as_update.update_fail_htlcs.is_empty()); // (5)
287         assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
288         assert!(as_update.update_fee.is_none()); // (5)
289         check_added_monitors!(nodes[0], 1);
290
291         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
292         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
293         // only (6) so get_event_msg's assert(len == 1) passes
294         check_added_monitors!(nodes[0], 1);
295
296         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
297         let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
298         check_added_monitors!(nodes[1], 1);
299
300         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
301         check_added_monitors!(nodes[0], 1);
302
303         let events_2 = nodes[0].node.get_and_clear_pending_events();
304         assert_eq!(events_2.len(), 1);
305         match events_2[0] {
306                 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
307                 _ => panic!("Unexpected event"),
308         }
309
310         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
311         check_added_monitors!(nodes[1], 1);
312 }
313
314 #[test]
315 fn test_update_fee_unordered_raa() {
316         // Just the intro to the previous test followed by an out-of-order RAA (which caused a
317         // crash in an earlier version of the update_fee patch)
318         let chanmon_cfgs = create_chanmon_cfgs(2);
319         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
320         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
321         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
322         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
323
324         // balancing
325         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
326
327         // First nodes[0] generates an update_fee
328         {
329                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
330                 *feerate_lock += 20;
331         }
332         nodes[0].node.timer_tick_occurred();
333         check_added_monitors!(nodes[0], 1);
334
335         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
336         assert_eq!(events_0.len(), 1);
337         let update_msg = match events_0[0] { // (1)
338                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
339                         update_fee.as_ref()
340                 },
341                 _ => panic!("Unexpected event"),
342         };
343
344         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
345
346         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
347         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
348         nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
349         check_added_monitors!(nodes[1], 1);
350
351         let payment_event = {
352                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
353                 assert_eq!(events_1.len(), 1);
354                 SendEvent::from_event(events_1.remove(0))
355         };
356         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
357         assert_eq!(payment_event.msgs.len(), 1);
358
359         // ...now when the messages get delivered everyone should be happy
360         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
361         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
362         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
363         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
364         check_added_monitors!(nodes[0], 1);
365
366         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
367         check_added_monitors!(nodes[1], 1);
368
369         // We can't continue, sadly, because our (1) now has a bogus signature
370 }
371
372 #[test]
373 fn test_multi_flight_update_fee() {
374         let chanmon_cfgs = create_chanmon_cfgs(2);
375         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
376         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
377         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
378         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
379
380         // A                                        B
381         // update_fee/commitment_signed          ->
382         //                                       .- send (1) RAA and (2) commitment_signed
383         // update_fee (never committed)          ->
384         // (3) update_fee                        ->
385         // We have to manually generate the above update_fee, it is allowed by the protocol but we
386         // don't track which updates correspond to which revoke_and_ack responses so we're in
387         // AwaitingRAA mode and will not generate the update_fee yet.
388         //                                       <- (1) RAA delivered
389         // (3) is generated and send (4) CS      -.
390         // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
391         // know the per_commitment_point to use for it.
392         //                                       <- (2) commitment_signed delivered
393         // revoke_and_ack                        ->
394         //                                          B should send no response here
395         // (4) commitment_signed delivered       ->
396         //                                       <- RAA/commitment_signed delivered
397         // revoke_and_ack                        ->
398
399         // First nodes[0] generates an update_fee
400         let initial_feerate;
401         {
402                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
403                 initial_feerate = *feerate_lock;
404                 *feerate_lock = initial_feerate + 20;
405         }
406         nodes[0].node.timer_tick_occurred();
407         check_added_monitors!(nodes[0], 1);
408
409         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
410         assert_eq!(events_0.len(), 1);
411         let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
412                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
413                         (update_fee.as_ref().unwrap(), commitment_signed)
414                 },
415                 _ => panic!("Unexpected event"),
416         };
417
418         // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
419         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
420         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
421         let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
422         check_added_monitors!(nodes[1], 1);
423
424         // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
425         // transaction:
426         {
427                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
428                 *feerate_lock = initial_feerate + 40;
429         }
430         nodes[0].node.timer_tick_occurred();
431         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
432         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
433
434         // Create the (3) update_fee message that nodes[0] will generate before it does...
435         let mut update_msg_2 = msgs::UpdateFee {
436                 channel_id: update_msg_1.channel_id.clone(),
437                 feerate_per_kw: (initial_feerate + 30) as u32,
438         };
439
440         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
441
442         update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
443         // Deliver (3)
444         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
445
446         // Deliver (1), generating (3) and (4)
447         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
448         let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
449         check_added_monitors!(nodes[0], 1);
450         assert!(as_second_update.update_add_htlcs.is_empty());
451         assert!(as_second_update.update_fulfill_htlcs.is_empty());
452         assert!(as_second_update.update_fail_htlcs.is_empty());
453         assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
454         // Check that the update_fee newly generated matches what we delivered:
455         assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
456         assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
457
458         // Deliver (2) commitment_signed
459         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
460         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
461         check_added_monitors!(nodes[0], 1);
462         // No commitment_signed so get_event_msg's assert(len == 1) passes
463
464         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
465         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
466         check_added_monitors!(nodes[1], 1);
467
468         // Delever (4)
469         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
470         let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
471         check_added_monitors!(nodes[1], 1);
472
473         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
474         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
475         check_added_monitors!(nodes[0], 1);
476
477         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
478         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
479         // No commitment_signed so get_event_msg's assert(len == 1) passes
480         check_added_monitors!(nodes[0], 1);
481
482         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
483         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
484         check_added_monitors!(nodes[1], 1);
485 }
486
487 fn do_test_sanity_on_in_flight_opens(steps: u8) {
488         // Previously, we had issues deserializing channels when we hadn't connected the first block
489         // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
490         // serialization round-trips and simply do steps towards opening a channel and then drop the
491         // Node objects.
492
493         let chanmon_cfgs = create_chanmon_cfgs(2);
494         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
495         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
496         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
497
498         if steps & 0b1000_0000 != 0{
499                 let block = Block {
500                         header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
501                         txdata: vec![],
502                 };
503                 connect_block(&nodes[0], &block);
504                 connect_block(&nodes[1], &block);
505         }
506
507         if steps & 0x0f == 0 { return; }
508         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
509         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
510
511         if steps & 0x0f == 1 { return; }
512         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
513         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
514
515         if steps & 0x0f == 2 { return; }
516         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
517
518         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
519
520         if steps & 0x0f == 3 { return; }
521         nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
522         check_added_monitors!(nodes[0], 0);
523         let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
524
525         if steps & 0x0f == 4 { return; }
526         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
527         {
528                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
529                 assert_eq!(added_monitors.len(), 1);
530                 assert_eq!(added_monitors[0].0, funding_output);
531                 added_monitors.clear();
532         }
533         let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
534
535         if steps & 0x0f == 5 { return; }
536         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
537         {
538                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
539                 assert_eq!(added_monitors.len(), 1);
540                 assert_eq!(added_monitors[0].0, funding_output);
541                 added_monitors.clear();
542         }
543
544         let events_4 = nodes[0].node.get_and_clear_pending_events();
545         assert_eq!(events_4.len(), 0);
546
547         if steps & 0x0f == 6 { return; }
548         create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
549
550         if steps & 0x0f == 7 { return; }
551         confirm_transaction_at(&nodes[0], &tx, 2);
552         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
553         create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
554 }
555
556 #[test]
557 fn test_sanity_on_in_flight_opens() {
558         do_test_sanity_on_in_flight_opens(0);
559         do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
560         do_test_sanity_on_in_flight_opens(1);
561         do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
562         do_test_sanity_on_in_flight_opens(2);
563         do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
564         do_test_sanity_on_in_flight_opens(3);
565         do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
566         do_test_sanity_on_in_flight_opens(4);
567         do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
568         do_test_sanity_on_in_flight_opens(5);
569         do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
570         do_test_sanity_on_in_flight_opens(6);
571         do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
572         do_test_sanity_on_in_flight_opens(7);
573         do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
574         do_test_sanity_on_in_flight_opens(8);
575         do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
576 }
577
578 #[test]
579 fn test_update_fee_vanilla() {
580         let chanmon_cfgs = create_chanmon_cfgs(2);
581         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
582         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
583         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
584         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
585
586         {
587                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
588                 *feerate_lock += 25;
589         }
590         nodes[0].node.timer_tick_occurred();
591         check_added_monitors!(nodes[0], 1);
592
593         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
594         assert_eq!(events_0.len(), 1);
595         let (update_msg, commitment_signed) = match events_0[0] {
596                         MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
597                         (update_fee.as_ref(), commitment_signed)
598                 },
599                 _ => panic!("Unexpected event"),
600         };
601         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
602
603         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
604         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
605         check_added_monitors!(nodes[1], 1);
606
607         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
608         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
609         check_added_monitors!(nodes[0], 1);
610
611         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
612         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
613         // No commitment_signed so get_event_msg's assert(len == 1) passes
614         check_added_monitors!(nodes[0], 1);
615
616         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
617         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
618         check_added_monitors!(nodes[1], 1);
619 }
620
621 #[test]
622 fn test_update_fee_that_funder_cannot_afford() {
623         let chanmon_cfgs = create_chanmon_cfgs(2);
624         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
625         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
626         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
627         let channel_value = 5000;
628         let push_sats = 700;
629         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, push_sats * 1000, InitFeatures::known(), InitFeatures::known());
630         let channel_id = chan.2;
631         let secp_ctx = Secp256k1::new();
632         let bs_channel_reserve_sats = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value);
633
634         let opt_anchors = false;
635
636         // Calculate the maximum feerate that A can afford. Note that we don't send an update_fee
637         // CONCURRENT_INBOUND_HTLC_FEE_BUFFER HTLCs before actually running out of local balance, so we
638         // calculate two different feerates here - the expected local limit as well as the expected
639         // remote limit.
640         let feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / (commitment_tx_base_weight(opt_anchors) + CONCURRENT_INBOUND_HTLC_FEE_BUFFER as u64 * COMMITMENT_TX_WEIGHT_PER_HTLC)) as u32;
641         let non_buffer_feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / commitment_tx_base_weight(opt_anchors)) as u32;
642         {
643                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
644                 *feerate_lock = feerate;
645         }
646         nodes[0].node.timer_tick_occurred();
647         check_added_monitors!(nodes[0], 1);
648         let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
649
650         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
651
652         commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
653
654         // Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate set above.
655         {
656                 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
657
658                 //We made sure neither party's funds are below the dust limit and there are no HTLCs here
659                 assert_eq!(commitment_tx.output.len(), 2);
660                 let total_fee: u64 = commit_tx_fee_msat(feerate, 0, opt_anchors) / 1000;
661                 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
662                 actual_fee = channel_value - actual_fee;
663                 assert_eq!(total_fee, actual_fee);
664         }
665
666         {
667                 // Increment the feerate by a small constant, accounting for rounding errors
668                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
669                 *feerate_lock += 4;
670         }
671         nodes[0].node.timer_tick_occurred();
672         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot afford to send new feerate at {}", feerate + 4), 1);
673         check_added_monitors!(nodes[0], 0);
674
675         const INITIAL_COMMITMENT_NUMBER: u64 = 281474976710654;
676
677         // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
678         // needed to sign the new commitment tx and (2) sign the new commitment tx.
679         let (local_revocation_basepoint, local_htlc_basepoint, local_funding) = {
680                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
681                 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
682                 let chan_signer = local_chan.get_signer();
683                 let pubkeys = chan_signer.pubkeys();
684                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
685                  pubkeys.funding_pubkey)
686         };
687         let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point, remote_funding) = {
688                 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
689                 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
690                 let chan_signer = remote_chan.get_signer();
691                 let pubkeys = chan_signer.pubkeys();
692                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
693                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
694                  pubkeys.funding_pubkey)
695         };
696
697         // Assemble the set of keys we can use for signatures for our commitment_signed message.
698         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
699                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
700
701         let res = {
702                 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
703                 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
704                 let local_chan_signer = local_chan.get_signer();
705                 let mut htlcs: Vec<(HTLCOutputInCommitment, ())> = vec![];
706                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
707                         INITIAL_COMMITMENT_NUMBER - 1,
708                         push_sats,
709                         channel_value - push_sats - commit_tx_fee_msat(non_buffer_feerate + 4, 0, opt_anchors) / 1000,
710                         opt_anchors, local_funding, remote_funding,
711                         commit_tx_keys.clone(),
712                         non_buffer_feerate + 4,
713                         &mut htlcs,
714                         &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
715                 );
716                 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
717         };
718
719         let commit_signed_msg = msgs::CommitmentSigned {
720                 channel_id: chan.2,
721                 signature: res.0,
722                 htlc_signatures: res.1
723         };
724
725         let update_fee = msgs::UpdateFee {
726                 channel_id: chan.2,
727                 feerate_per_kw: non_buffer_feerate + 4,
728         };
729
730         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_fee);
731
732         //While producing the commitment_signed response after handling a received update_fee request the
733         //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
734         //Should produce and error.
735         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
736         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
737         check_added_monitors!(nodes[1], 1);
738         check_closed_broadcast!(nodes[1], true);
739         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: String::from("Funding remote cannot afford proposed new fee") });
740 }
741
742 #[test]
743 fn test_update_fee_with_fundee_update_add_htlc() {
744         let chanmon_cfgs = create_chanmon_cfgs(2);
745         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
746         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
747         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
748         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
749
750         // balancing
751         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
752
753         {
754                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
755                 *feerate_lock += 20;
756         }
757         nodes[0].node.timer_tick_occurred();
758         check_added_monitors!(nodes[0], 1);
759
760         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
761         assert_eq!(events_0.len(), 1);
762         let (update_msg, commitment_signed) = match events_0[0] {
763                         MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
764                         (update_fee.as_ref(), commitment_signed)
765                 },
766                 _ => panic!("Unexpected event"),
767         };
768         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
769         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
770         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
771         check_added_monitors!(nodes[1], 1);
772
773         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 800000);
774
775         // nothing happens since node[1] is in AwaitingRemoteRevoke
776         nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
777         {
778                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
779                 assert_eq!(added_monitors.len(), 0);
780                 added_monitors.clear();
781         }
782         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
783         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
784         // node[1] has nothing to do
785
786         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
787         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
788         check_added_monitors!(nodes[0], 1);
789
790         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
791         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
792         // No commitment_signed so get_event_msg's assert(len == 1) passes
793         check_added_monitors!(nodes[0], 1);
794         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
795         check_added_monitors!(nodes[1], 1);
796         // AwaitingRemoteRevoke ends here
797
798         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
799         assert_eq!(commitment_update.update_add_htlcs.len(), 1);
800         assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
801         assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
802         assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
803         assert_eq!(commitment_update.update_fee.is_none(), true);
804
805         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
806         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
807         check_added_monitors!(nodes[0], 1);
808         let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
809
810         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
811         check_added_monitors!(nodes[1], 1);
812         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
813
814         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
815         check_added_monitors!(nodes[1], 1);
816         let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
817         // No commitment_signed so get_event_msg's assert(len == 1) passes
818
819         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
820         check_added_monitors!(nodes[0], 1);
821         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
822
823         expect_pending_htlcs_forwardable!(nodes[0]);
824
825         let events = nodes[0].node.get_and_clear_pending_events();
826         assert_eq!(events.len(), 1);
827         match events[0] {
828                 Event::PaymentReceived { .. } => { },
829                 _ => panic!("Unexpected event"),
830         };
831
832         claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
833
834         send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
835         send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
836         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
837         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
838         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
839 }
840
841 #[test]
842 fn test_update_fee() {
843         let chanmon_cfgs = create_chanmon_cfgs(2);
844         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
845         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
846         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
847         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
848         let channel_id = chan.2;
849
850         // A                                        B
851         // (1) update_fee/commitment_signed      ->
852         //                                       <- (2) revoke_and_ack
853         //                                       .- send (3) commitment_signed
854         // (4) update_fee/commitment_signed      ->
855         //                                       .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
856         //                                       <- (3) commitment_signed delivered
857         // send (6) revoke_and_ack               -.
858         //                                       <- (5) deliver revoke_and_ack
859         // (6) deliver revoke_and_ack            ->
860         //                                       .- send (7) commitment_signed in response to (4)
861         //                                       <- (7) deliver commitment_signed
862         // revoke_and_ack                        ->
863
864         // Create and deliver (1)...
865         let feerate;
866         {
867                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
868                 feerate = *feerate_lock;
869                 *feerate_lock = feerate + 20;
870         }
871         nodes[0].node.timer_tick_occurred();
872         check_added_monitors!(nodes[0], 1);
873
874         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
875         assert_eq!(events_0.len(), 1);
876         let (update_msg, commitment_signed) = match events_0[0] {
877                         MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
878                         (update_fee.as_ref(), commitment_signed)
879                 },
880                 _ => panic!("Unexpected event"),
881         };
882         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
883
884         // Generate (2) and (3):
885         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
886         let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
887         check_added_monitors!(nodes[1], 1);
888
889         // Deliver (2):
890         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
891         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
892         check_added_monitors!(nodes[0], 1);
893
894         // Create and deliver (4)...
895         {
896                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
897                 *feerate_lock = feerate + 30;
898         }
899         nodes[0].node.timer_tick_occurred();
900         check_added_monitors!(nodes[0], 1);
901         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
902         assert_eq!(events_0.len(), 1);
903         let (update_msg, commitment_signed) = match events_0[0] {
904                         MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
905                         (update_fee.as_ref(), commitment_signed)
906                 },
907                 _ => panic!("Unexpected event"),
908         };
909
910         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
911         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
912         check_added_monitors!(nodes[1], 1);
913         // ... creating (5)
914         let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
915         // No commitment_signed so get_event_msg's assert(len == 1) passes
916
917         // Handle (3), creating (6):
918         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
919         check_added_monitors!(nodes[0], 1);
920         let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
921         // No commitment_signed so get_event_msg's assert(len == 1) passes
922
923         // Deliver (5):
924         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
925         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
926         check_added_monitors!(nodes[0], 1);
927
928         // Deliver (6), creating (7):
929         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
930         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
931         assert!(commitment_update.update_add_htlcs.is_empty());
932         assert!(commitment_update.update_fulfill_htlcs.is_empty());
933         assert!(commitment_update.update_fail_htlcs.is_empty());
934         assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
935         assert!(commitment_update.update_fee.is_none());
936         check_added_monitors!(nodes[1], 1);
937
938         // Deliver (7)
939         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
940         check_added_monitors!(nodes[0], 1);
941         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
942         // No commitment_signed so get_event_msg's assert(len == 1) passes
943
944         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
945         check_added_monitors!(nodes[1], 1);
946         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
947
948         assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
949         assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
950         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
951         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
952         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
953 }
954
955 #[test]
956 fn fake_network_test() {
957         // Simple test which builds a network of ChannelManagers, connects them to each other, and
958         // tests that payments get routed and transactions broadcast in semi-reasonable ways.
959         let chanmon_cfgs = create_chanmon_cfgs(4);
960         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
961         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
962         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
963
964         // Create some initial channels
965         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
966         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
967         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
968
969         // Rebalance the network a bit by relaying one payment through all the channels...
970         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
971         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
972         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
973         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
974
975         // Send some more payments
976         send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
977         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
978         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
979
980         // Test failure packets
981         let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
982         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
983
984         // Add a new channel that skips 3
985         let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
986
987         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
988         send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
989         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
990         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
991         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
992         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
993         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
994
995         // Do some rebalance loop payments, simultaneously
996         let mut hops = Vec::with_capacity(3);
997         hops.push(RouteHop {
998                 pubkey: nodes[2].node.get_our_node_id(),
999                 node_features: NodeFeatures::empty(),
1000                 short_channel_id: chan_2.0.contents.short_channel_id,
1001                 channel_features: ChannelFeatures::empty(),
1002                 fee_msat: 0,
1003                 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1004         });
1005         hops.push(RouteHop {
1006                 pubkey: nodes[3].node.get_our_node_id(),
1007                 node_features: NodeFeatures::empty(),
1008                 short_channel_id: chan_3.0.contents.short_channel_id,
1009                 channel_features: ChannelFeatures::empty(),
1010                 fee_msat: 0,
1011                 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1012         });
1013         hops.push(RouteHop {
1014                 pubkey: nodes[1].node.get_our_node_id(),
1015                 node_features: NodeFeatures::known(),
1016                 short_channel_id: chan_4.0.contents.short_channel_id,
1017                 channel_features: ChannelFeatures::known(),
1018                 fee_msat: 1000000,
1019                 cltv_expiry_delta: TEST_FINAL_CLTV,
1020         });
1021         hops[1].fee_msat = chan_4.1.contents.fee_base_msat as u64 + chan_4.1.contents.fee_proportional_millionths as u64 * hops[2].fee_msat as u64 / 1000000;
1022         hops[0].fee_msat = chan_3.0.contents.fee_base_msat as u64 + chan_3.0.contents.fee_proportional_millionths as u64 * hops[1].fee_msat as u64 / 1000000;
1023         let payment_preimage_1 = send_along_route(&nodes[1], Route { paths: vec![hops], payment_params: None }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1024
1025         let mut hops = Vec::with_capacity(3);
1026         hops.push(RouteHop {
1027                 pubkey: nodes[3].node.get_our_node_id(),
1028                 node_features: NodeFeatures::empty(),
1029                 short_channel_id: chan_4.0.contents.short_channel_id,
1030                 channel_features: ChannelFeatures::empty(),
1031                 fee_msat: 0,
1032                 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1033         });
1034         hops.push(RouteHop {
1035                 pubkey: nodes[2].node.get_our_node_id(),
1036                 node_features: NodeFeatures::empty(),
1037                 short_channel_id: chan_3.0.contents.short_channel_id,
1038                 channel_features: ChannelFeatures::empty(),
1039                 fee_msat: 0,
1040                 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1041         });
1042         hops.push(RouteHop {
1043                 pubkey: nodes[1].node.get_our_node_id(),
1044                 node_features: NodeFeatures::known(),
1045                 short_channel_id: chan_2.0.contents.short_channel_id,
1046                 channel_features: ChannelFeatures::known(),
1047                 fee_msat: 1000000,
1048                 cltv_expiry_delta: TEST_FINAL_CLTV,
1049         });
1050         hops[1].fee_msat = chan_2.1.contents.fee_base_msat as u64 + chan_2.1.contents.fee_proportional_millionths as u64 * hops[2].fee_msat as u64 / 1000000;
1051         hops[0].fee_msat = chan_3.1.contents.fee_base_msat as u64 + chan_3.1.contents.fee_proportional_millionths as u64 * hops[1].fee_msat as u64 / 1000000;
1052         let payment_hash_2 = send_along_route(&nodes[1], Route { paths: vec![hops], payment_params: None }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1053
1054         // Claim the rebalances...
1055         fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1056         claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1057
1058         // Add a duplicate new channel from 2 to 4
1059         let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1060
1061         // Send some payments across both channels
1062         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1063         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1064         let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1065
1066
1067         route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
1068         let events = nodes[0].node.get_and_clear_pending_msg_events();
1069         assert_eq!(events.len(), 0);
1070         nodes[0].logger.assert_log_regex("lightning::ln::channelmanager".to_string(), regex::Regex::new(r"Cannot send value that would put us over the max HTLC value in flight our peer will accept \(\d+\)").unwrap(), 1);
1071
1072         //TODO: Test that routes work again here as we've been notified that the channel is full
1073
1074         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3);
1075         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4);
1076         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5);
1077
1078         // Close down the channels...
1079         close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1080         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
1081         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1082         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1083         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1084         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1085         close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1086         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1087         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1088         close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1089         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1090         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1091         close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
1092         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1093         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1094 }
1095
1096 #[test]
1097 fn holding_cell_htlc_counting() {
1098         // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1099         // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1100         // commitment dance rounds.
1101         let chanmon_cfgs = create_chanmon_cfgs(3);
1102         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1103         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1104         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1105         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1106         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1107
1108         let mut payments = Vec::new();
1109         for _ in 0..::ln::channel::OUR_MAX_HTLCS {
1110                 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1111                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
1112                 payments.push((payment_preimage, payment_hash));
1113         }
1114         check_added_monitors!(nodes[1], 1);
1115
1116         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1117         assert_eq!(events.len(), 1);
1118         let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1119         assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1120
1121         // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1122         // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1123         // another HTLC.
1124         let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1125         {
1126                 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)), true, APIError::ChannelUnavailable { ref err },
1127                         assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1128                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1129                 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1130         }
1131
1132         // This should also be true if we try to forward a payment.
1133         let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1134         {
1135                 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
1136                 check_added_monitors!(nodes[0], 1);
1137         }
1138
1139         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1140         assert_eq!(events.len(), 1);
1141         let payment_event = SendEvent::from_event(events.pop().unwrap());
1142         assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1143
1144         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1145         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1146         // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1147         // fails), the second will process the resulting failure and fail the HTLC backward.
1148         expect_pending_htlcs_forwardable!(nodes[1]);
1149         expect_pending_htlcs_forwardable!(nodes[1]);
1150         check_added_monitors!(nodes[1], 1);
1151
1152         let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1153         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1154         commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1155
1156         expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1157
1158         // Now forward all the pending HTLCs and claim them back
1159         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1160         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1161         check_added_monitors!(nodes[2], 1);
1162
1163         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1164         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1165         check_added_monitors!(nodes[1], 1);
1166         let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1167
1168         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1169         check_added_monitors!(nodes[1], 1);
1170         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1171
1172         for ref update in as_updates.update_add_htlcs.iter() {
1173                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1174         }
1175         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1176         check_added_monitors!(nodes[2], 1);
1177         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1178         check_added_monitors!(nodes[2], 1);
1179         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1180
1181         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1182         check_added_monitors!(nodes[1], 1);
1183         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1184         check_added_monitors!(nodes[1], 1);
1185         let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1186
1187         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1188         check_added_monitors!(nodes[2], 1);
1189
1190         expect_pending_htlcs_forwardable!(nodes[2]);
1191
1192         let events = nodes[2].node.get_and_clear_pending_events();
1193         assert_eq!(events.len(), payments.len());
1194         for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1195                 match event {
1196                         &Event::PaymentReceived { ref payment_hash, .. } => {
1197                                 assert_eq!(*payment_hash, *hash);
1198                         },
1199                         _ => panic!("Unexpected event"),
1200                 };
1201         }
1202
1203         for (preimage, _) in payments.drain(..) {
1204                 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1205         }
1206
1207         send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1208 }
1209
1210 #[test]
1211 fn duplicate_htlc_test() {
1212         // Test that we accept duplicate payment_hash HTLCs across the network and that
1213         // claiming/failing them are all separate and don't affect each other
1214         let chanmon_cfgs = create_chanmon_cfgs(6);
1215         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1216         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1217         let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1218
1219         // Create some initial channels to route via 3 to 4/5 from 0/1/2
1220         create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
1221         create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1222         create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1223         create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
1224         create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
1225
1226         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1227
1228         *nodes[0].network_payment_count.borrow_mut() -= 1;
1229         assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1230
1231         *nodes[0].network_payment_count.borrow_mut() -= 1;
1232         assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1233
1234         claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1235         fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1236         claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1237 }
1238
1239 #[test]
1240 fn test_duplicate_htlc_different_direction_onchain() {
1241         // Test that ChannelMonitor doesn't generate 2 preimage txn
1242         // when we have 2 HTLCs with same preimage that go across a node
1243         // in opposite directions, even with the same payment secret.
1244         let chanmon_cfgs = create_chanmon_cfgs(2);
1245         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1246         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1247         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1248
1249         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1250
1251         // balancing
1252         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1253
1254         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1255
1256         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1257         let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200).unwrap();
1258         send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1259
1260         // Provide preimage to node 0 by claiming payment
1261         nodes[0].node.claim_funds(payment_preimage);
1262         check_added_monitors!(nodes[0], 1);
1263
1264         // Broadcast node 1 commitment txn
1265         let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1266
1267         assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1268         let mut has_both_htlcs = 0; // check htlcs match ones committed
1269         for outp in remote_txn[0].output.iter() {
1270                 if outp.value == 800_000 / 1000 {
1271                         has_both_htlcs += 1;
1272                 } else if outp.value == 900_000 / 1000 {
1273                         has_both_htlcs += 1;
1274                 }
1275         }
1276         assert_eq!(has_both_htlcs, 2);
1277
1278         mine_transaction(&nodes[0], &remote_txn[0]);
1279         check_added_monitors!(nodes[0], 1);
1280         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
1281         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
1282
1283         // 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.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
2182         check_added_monitors!(nodes[1], 1);
2183         check_closed_broadcast!(nodes[1], false);
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::DisconnectedPeer);
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.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
2203         check_closed_broadcast!(nodes[1], false);
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::DisconnectedPeer);
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.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
2242         check_added_monitors!(nodes[2], 1);
2243         check_closed_broadcast!(nodes[2], false);
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::DisconnectedPeer);
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, source_channel_id, claim_from_onchain_tx } => {
2712                         assert_eq!(fee_earned_msat, Some(1000));
2713                         assert_eq!(source_channel_id, chan_id);
2714                         assert_eq!(claim_from_onchain_tx, true);
2715                 },
2716                 _ => panic!()
2717         }
2718         match forwarded_events[2] {
2719                 Event::PaymentForwarded { fee_earned_msat, source_channel_id, claim_from_onchain_tx } => {
2720                         assert_eq!(fee_earned_msat, Some(1000));
2721                         assert_eq!(source_channel_id, chan_id);
2722                         assert_eq!(claim_from_onchain_tx, true);
2723                 },
2724                 _ => panic!()
2725         }
2726         let events = nodes[1].node.get_and_clear_pending_msg_events();
2727         {
2728                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2729                 assert_eq!(added_monitors.len(), 2);
2730                 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2731                 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2732                 added_monitors.clear();
2733         }
2734         assert_eq!(events.len(), 3);
2735         match events[0] {
2736                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2737                 _ => panic!("Unexpected event"),
2738         }
2739         match events[1] {
2740                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2741                 _ => panic!("Unexpected event"),
2742         }
2743
2744         match events[2] {
2745                 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, .. } } => {
2746                         assert!(update_add_htlcs.is_empty());
2747                         assert!(update_fail_htlcs.is_empty());
2748                         assert_eq!(update_fulfill_htlcs.len(), 1);
2749                         assert!(update_fail_malformed_htlcs.is_empty());
2750                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2751                 },
2752                 _ => panic!("Unexpected event"),
2753         };
2754         macro_rules! check_tx_local_broadcast {
2755                 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2756                         let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2757                         assert_eq!(node_txn.len(), 3);
2758                         // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2759                         // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2760                         check_spends!(node_txn[1], $commitment_tx);
2761                         check_spends!(node_txn[2], $commitment_tx);
2762                         assert_ne!(node_txn[1].lock_time, 0);
2763                         assert_ne!(node_txn[2].lock_time, 0);
2764                         if $htlc_offered {
2765                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2766                                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2767                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2768                                 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2769                         } else {
2770                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2771                                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2772                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2773                                 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2774                         }
2775                         check_spends!(node_txn[0], $chan_tx);
2776                         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2777                         node_txn.clear();
2778                 } }
2779         }
2780         // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2781         // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2782         // timeout-claim of the output that nodes[2] just claimed via success.
2783         check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2784
2785         // Broadcast legit commitment tx from A on B's chain
2786         // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
2787         let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2788         check_spends!(node_a_commitment_tx[0], chan_1.3);
2789         mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2790         check_closed_broadcast!(nodes[1], true);
2791         check_added_monitors!(nodes[1], 1);
2792         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2793         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2794         assert_eq!(node_txn.len(), 6); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 3 (HTLC-Success, 2* RBF bumps of above HTLC txn)
2795         let commitment_spend =
2796                 if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2797                         check_spends!(node_txn[1], commitment_tx[0]);
2798                         check_spends!(node_txn[2], commitment_tx[0]);
2799                         assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2800                         &node_txn[0]
2801                 } else {
2802                         check_spends!(node_txn[0], commitment_tx[0]);
2803                         check_spends!(node_txn[1], commitment_tx[0]);
2804                         assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2805                         &node_txn[2]
2806                 };
2807
2808         check_spends!(commitment_spend, node_a_commitment_tx[0]);
2809         assert_eq!(commitment_spend.input.len(), 2);
2810         assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2811         assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2812         assert_eq!(commitment_spend.lock_time, 0);
2813         assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2814         check_spends!(node_txn[3], chan_1.3);
2815         assert_eq!(node_txn[3].input[0].witness.clone().last().unwrap().len(), 71);
2816         check_spends!(node_txn[4], node_txn[3]);
2817         check_spends!(node_txn[5], node_txn[3]);
2818         // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2819         // we already checked the same situation with A.
2820
2821         // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2822         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2823         connect_block(&nodes[0], &Block { header, txdata: vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()] });
2824         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2825         check_closed_broadcast!(nodes[0], true);
2826         check_added_monitors!(nodes[0], 1);
2827         let events = nodes[0].node.get_and_clear_pending_events();
2828         assert_eq!(events.len(), 5);
2829         let mut first_claimed = false;
2830         for event in events {
2831                 match event {
2832                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
2833                                 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
2834                                         assert!(!first_claimed);
2835                                         first_claimed = true;
2836                                 } else {
2837                                         assert_eq!(payment_preimage, our_payment_preimage_2);
2838                                         assert_eq!(payment_hash, payment_hash_2);
2839                                 }
2840                         },
2841                         Event::PaymentPathSuccessful { .. } => {},
2842                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
2843                         _ => panic!("Unexpected event"),
2844                 }
2845         }
2846         check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0], chan_1.3);
2847 }
2848
2849 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2850         // Test that in case of a unilateral close onchain, we detect the state of output and
2851         // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2852         // broadcasting the right event to other nodes in payment path.
2853         // A ------------------> B ----------------------> C (timeout)
2854         //    B's commitment tx                 C's commitment tx
2855         //            \                                  \
2856         //         B's HTLC timeout tx               B's timeout tx
2857
2858         let chanmon_cfgs = create_chanmon_cfgs(3);
2859         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2860         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2861         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2862         *nodes[0].connect_style.borrow_mut() = connect_style;
2863         *nodes[1].connect_style.borrow_mut() = connect_style;
2864         *nodes[2].connect_style.borrow_mut() = connect_style;
2865
2866         // Create some intial channels
2867         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2868         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2869
2870         // Rebalance the network a bit by relaying one payment thorugh all the channels...
2871         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2872         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2873
2874         let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2875
2876         // Broadcast legit commitment tx from C on B's chain
2877         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2878         check_spends!(commitment_tx[0], chan_2.3);
2879         nodes[2].node.fail_htlc_backwards(&payment_hash);
2880         check_added_monitors!(nodes[2], 0);
2881         expect_pending_htlcs_forwardable!(nodes[2]);
2882         check_added_monitors!(nodes[2], 1);
2883
2884         let events = nodes[2].node.get_and_clear_pending_msg_events();
2885         assert_eq!(events.len(), 1);
2886         match events[0] {
2887                 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, .. } } => {
2888                         assert!(update_add_htlcs.is_empty());
2889                         assert!(!update_fail_htlcs.is_empty());
2890                         assert!(update_fulfill_htlcs.is_empty());
2891                         assert!(update_fail_malformed_htlcs.is_empty());
2892                         assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2893                 },
2894                 _ => panic!("Unexpected event"),
2895         };
2896         mine_transaction(&nodes[2], &commitment_tx[0]);
2897         check_closed_broadcast!(nodes[2], true);
2898         check_added_monitors!(nodes[2], 1);
2899         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2900         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2901         assert_eq!(node_txn.len(), 1);
2902         check_spends!(node_txn[0], chan_2.3);
2903         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2904
2905         // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2906         // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2907         connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2908         mine_transaction(&nodes[1], &commitment_tx[0]);
2909         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2910         let timeout_tx;
2911         {
2912                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2913                 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
2914                 assert_eq!(node_txn[0], node_txn[3]);
2915                 assert_eq!(node_txn[1], node_txn[4]);
2916
2917                 check_spends!(node_txn[2], commitment_tx[0]);
2918                 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2919
2920                 check_spends!(node_txn[0], chan_2.3);
2921                 check_spends!(node_txn[1], node_txn[0]);
2922                 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2923                 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2924
2925                 timeout_tx = node_txn[2].clone();
2926                 node_txn.clear();
2927         }
2928
2929         mine_transaction(&nodes[1], &timeout_tx);
2930         check_added_monitors!(nodes[1], 1);
2931         check_closed_broadcast!(nodes[1], true);
2932         {
2933                 // B will rebroadcast a fee-bumped timeout transaction here.
2934                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2935                 assert_eq!(node_txn.len(), 1);
2936                 check_spends!(node_txn[0], commitment_tx[0]);
2937         }
2938
2939         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2940         {
2941                 // B may rebroadcast its own holder commitment transaction here, as a safeguard against
2942                 // some incredibly unlikely partial-eclipse-attack scenarios. That said, because the
2943                 // original commitment_tx[0] (also spending chan_2.3) has reached ANTI_REORG_DELAY B really
2944                 // shouldn't broadcast anything here, and in some connect style scenarios we do not.
2945                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2946                 if node_txn.len() == 1 {
2947                         check_spends!(node_txn[0], chan_2.3);
2948                 } else {
2949                         assert_eq!(node_txn.len(), 0);
2950                 }
2951         }
2952
2953         expect_pending_htlcs_forwardable!(nodes[1]);
2954         check_added_monitors!(nodes[1], 1);
2955         let events = nodes[1].node.get_and_clear_pending_msg_events();
2956         assert_eq!(events.len(), 1);
2957         match events[0] {
2958                 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, .. } } => {
2959                         assert!(update_add_htlcs.is_empty());
2960                         assert!(!update_fail_htlcs.is_empty());
2961                         assert!(update_fulfill_htlcs.is_empty());
2962                         assert!(update_fail_malformed_htlcs.is_empty());
2963                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2964                 },
2965                 _ => panic!("Unexpected event"),
2966         };
2967
2968         // Broadcast legit commitment tx from B on A's chain
2969         let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
2970         check_spends!(commitment_tx[0], chan_1.3);
2971
2972         mine_transaction(&nodes[0], &commitment_tx[0]);
2973         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2974
2975         check_closed_broadcast!(nodes[0], true);
2976         check_added_monitors!(nodes[0], 1);
2977         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2978         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 commitment tx, ChannelMonitor : 1 timeout tx
2979         assert_eq!(node_txn.len(), 2);
2980         check_spends!(node_txn[0], chan_1.3);
2981         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2982         check_spends!(node_txn[1], commitment_tx[0]);
2983         assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2984 }
2985
2986 #[test]
2987 fn test_htlc_on_chain_timeout() {
2988         do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
2989         do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
2990         do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
2991 }
2992
2993 #[test]
2994 fn test_simple_commitment_revoked_fail_backward() {
2995         // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
2996         // and fail backward accordingly.
2997
2998         let chanmon_cfgs = create_chanmon_cfgs(3);
2999         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3000         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3001         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3002
3003         // Create some initial channels
3004         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3005         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3006
3007         let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3008         // Get the will-be-revoked local txn from nodes[2]
3009         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3010         // Revoke the old state
3011         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3012
3013         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3014
3015         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3016         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3017         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3018         check_added_monitors!(nodes[1], 1);
3019         check_closed_broadcast!(nodes[1], true);
3020
3021         expect_pending_htlcs_forwardable!(nodes[1]);
3022         check_added_monitors!(nodes[1], 1);
3023         let events = nodes[1].node.get_and_clear_pending_msg_events();
3024         assert_eq!(events.len(), 1);
3025         match events[0] {
3026                 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, .. } } => {
3027                         assert!(update_add_htlcs.is_empty());
3028                         assert_eq!(update_fail_htlcs.len(), 1);
3029                         assert!(update_fulfill_htlcs.is_empty());
3030                         assert!(update_fail_malformed_htlcs.is_empty());
3031                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3032
3033                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3034                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3035                         expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3036                 },
3037                 _ => panic!("Unexpected event"),
3038         }
3039 }
3040
3041 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3042         // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3043         // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3044         // commitment transaction anymore.
3045         // To do this, we have the peer which will broadcast a revoked commitment transaction send
3046         // a number of update_fail/commitment_signed updates without ever sending the RAA in
3047         // response to our commitment_signed. This is somewhat misbehavior-y, though not
3048         // technically disallowed and we should probably handle it reasonably.
3049         // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3050         // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3051         // transactions:
3052         // * Once we move it out of our holding cell/add it, we will immediately include it in a
3053         //   commitment_signed (implying it will be in the latest remote commitment transaction).
3054         // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3055         //   and once they revoke the previous commitment transaction (allowing us to send a new
3056         //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3057         let chanmon_cfgs = create_chanmon_cfgs(3);
3058         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3059         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3060         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3061
3062         // Create some initial channels
3063         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3064         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3065
3066         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 });
3067         // Get the will-be-revoked local txn from nodes[2]
3068         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3069         assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3070         // Revoke the old state
3071         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3072
3073         let value = if use_dust {
3074                 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3075                 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3076                 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3077         } else { 3000000 };
3078
3079         let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3080         let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3081         let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3082
3083         assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash));
3084         expect_pending_htlcs_forwardable!(nodes[2]);
3085         check_added_monitors!(nodes[2], 1);
3086         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3087         assert!(updates.update_add_htlcs.is_empty());
3088         assert!(updates.update_fulfill_htlcs.is_empty());
3089         assert!(updates.update_fail_malformed_htlcs.is_empty());
3090         assert_eq!(updates.update_fail_htlcs.len(), 1);
3091         assert!(updates.update_fee.is_none());
3092         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3093         let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3094         // Drop the last RAA from 3 -> 2
3095
3096         assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash));
3097         expect_pending_htlcs_forwardable!(nodes[2]);
3098         check_added_monitors!(nodes[2], 1);
3099         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3100         assert!(updates.update_add_htlcs.is_empty());
3101         assert!(updates.update_fulfill_htlcs.is_empty());
3102         assert!(updates.update_fail_malformed_htlcs.is_empty());
3103         assert_eq!(updates.update_fail_htlcs.len(), 1);
3104         assert!(updates.update_fee.is_none());
3105         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3106         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3107         check_added_monitors!(nodes[1], 1);
3108         // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3109         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3110         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3111         check_added_monitors!(nodes[2], 1);
3112
3113         assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash));
3114         expect_pending_htlcs_forwardable!(nodes[2]);
3115         check_added_monitors!(nodes[2], 1);
3116         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3117         assert!(updates.update_add_htlcs.is_empty());
3118         assert!(updates.update_fulfill_htlcs.is_empty());
3119         assert!(updates.update_fail_malformed_htlcs.is_empty());
3120         assert_eq!(updates.update_fail_htlcs.len(), 1);
3121         assert!(updates.update_fee.is_none());
3122         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3123         // At this point first_payment_hash has dropped out of the latest two commitment
3124         // transactions that nodes[1] is tracking...
3125         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3126         check_added_monitors!(nodes[1], 1);
3127         // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3128         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3129         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3130         check_added_monitors!(nodes[2], 1);
3131
3132         // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3133         // on nodes[2]'s RAA.
3134         let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3135         nodes[1].node.send_payment(&route, fourth_payment_hash, &Some(fourth_payment_secret)).unwrap();
3136         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3137         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3138         check_added_monitors!(nodes[1], 0);
3139
3140         if deliver_bs_raa {
3141                 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3142                 // One monitor for the new revocation preimage, no second on as we won't generate a new
3143                 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3144                 check_added_monitors!(nodes[1], 1);
3145                 let events = nodes[1].node.get_and_clear_pending_events();
3146                 assert_eq!(events.len(), 1);
3147                 match events[0] {
3148                         Event::PendingHTLCsForwardable { .. } => { },
3149                         _ => panic!("Unexpected event"),
3150                 };
3151                 // Deliberately don't process the pending fail-back so they all fail back at once after
3152                 // block connection just like the !deliver_bs_raa case
3153         }
3154
3155         let mut failed_htlcs = HashSet::new();
3156         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3157
3158         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3159         check_added_monitors!(nodes[1], 1);
3160         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3161         assert!(ANTI_REORG_DELAY > PAYMENT_EXPIRY_BLOCKS); // We assume payments will also expire
3162
3163         let events = nodes[1].node.get_and_clear_pending_events();
3164         assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 4 });
3165         match events[0] {
3166                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3167                 _ => panic!("Unexepected event"),
3168         }
3169         match events[1] {
3170                 Event::PaymentPathFailed { ref payment_hash, .. } => {
3171                         assert_eq!(*payment_hash, fourth_payment_hash);
3172                 },
3173                 _ => panic!("Unexpected event"),
3174         }
3175         if !deliver_bs_raa {
3176                 match events[2] {
3177                         Event::PaymentFailed { ref payment_hash, .. } => {
3178                                 assert_eq!(*payment_hash, fourth_payment_hash);
3179                         },
3180                         _ => panic!("Unexpected event"),
3181                 }
3182                 match events[3] {
3183                         Event::PendingHTLCsForwardable { .. } => { },
3184                         _ => panic!("Unexpected event"),
3185                 };
3186         }
3187         nodes[1].node.process_pending_htlc_forwards();
3188         check_added_monitors!(nodes[1], 1);
3189
3190         let events = nodes[1].node.get_and_clear_pending_msg_events();
3191         assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3192         match events[if deliver_bs_raa { 1 } else { 0 }] {
3193                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3194                 _ => panic!("Unexpected event"),
3195         }
3196         match events[if deliver_bs_raa { 2 } else { 1 }] {
3197                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3198                         assert_eq!(channel_id, chan_2.2);
3199                         assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3200                 },
3201                 _ => panic!("Unexpected event"),
3202         }
3203         if deliver_bs_raa {
3204                 match events[0] {
3205                         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, .. } } => {
3206                                 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3207                                 assert_eq!(update_add_htlcs.len(), 1);
3208                                 assert!(update_fulfill_htlcs.is_empty());
3209                                 assert!(update_fail_htlcs.is_empty());
3210                                 assert!(update_fail_malformed_htlcs.is_empty());
3211                         },
3212                         _ => panic!("Unexpected event"),
3213                 }
3214         }
3215         match events[if deliver_bs_raa { 3 } else { 2 }] {
3216                 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, .. } } => {
3217                         assert!(update_add_htlcs.is_empty());
3218                         assert_eq!(update_fail_htlcs.len(), 3);
3219                         assert!(update_fulfill_htlcs.is_empty());
3220                         assert!(update_fail_malformed_htlcs.is_empty());
3221                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3222
3223                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3224                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3225                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3226
3227                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3228
3229                         let events = nodes[0].node.get_and_clear_pending_events();
3230                         assert_eq!(events.len(), 3);
3231                         match events[0] {
3232                                 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3233                                         assert!(failed_htlcs.insert(payment_hash.0));
3234                                         // If we delivered B's RAA we got an unknown preimage error, not something
3235                                         // that we should update our routing table for.
3236                                         if !deliver_bs_raa {
3237                                                 assert!(network_update.is_some());
3238                                         }
3239                                 },
3240                                 _ => panic!("Unexpected event"),
3241                         }
3242                         match events[1] {
3243                                 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3244                                         assert!(failed_htlcs.insert(payment_hash.0));
3245                                         assert!(network_update.is_some());
3246                                 },
3247                                 _ => panic!("Unexpected event"),
3248                         }
3249                         match events[2] {
3250                                 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3251                                         assert!(failed_htlcs.insert(payment_hash.0));
3252                                         assert!(network_update.is_some());
3253                                 },
3254                                 _ => panic!("Unexpected event"),
3255                         }
3256                 },
3257                 _ => panic!("Unexpected event"),
3258         }
3259
3260         assert!(failed_htlcs.contains(&first_payment_hash.0));
3261         assert!(failed_htlcs.contains(&second_payment_hash.0));
3262         assert!(failed_htlcs.contains(&third_payment_hash.0));
3263 }
3264
3265 #[test]
3266 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3267         do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3268         do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3269         do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3270         do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3271 }
3272
3273 #[test]
3274 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3275         do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3276         do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3277         do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3278         do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3279 }
3280
3281 #[test]
3282 fn fail_backward_pending_htlc_upon_channel_failure() {
3283         let chanmon_cfgs = create_chanmon_cfgs(2);
3284         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3285         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3286         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3287         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
3288
3289         // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3290         {
3291                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3292                 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
3293                 check_added_monitors!(nodes[0], 1);
3294
3295                 let payment_event = {
3296                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3297                         assert_eq!(events.len(), 1);
3298                         SendEvent::from_event(events.remove(0))
3299                 };
3300                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3301                 assert_eq!(payment_event.msgs.len(), 1);
3302         }
3303
3304         // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3305         let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3306         {
3307                 nodes[0].node.send_payment(&route, failed_payment_hash, &Some(failed_payment_secret)).unwrap();
3308                 check_added_monitors!(nodes[0], 0);
3309
3310                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3311         }
3312
3313         // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3314         {
3315                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3316
3317                 let secp_ctx = Secp256k1::new();
3318                 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3319                 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3320                 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &Some(payment_secret), current_height, &None).unwrap();
3321                 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3322                 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3323
3324                 // Send a 0-msat update_add_htlc to fail the channel.
3325                 let update_add_htlc = msgs::UpdateAddHTLC {
3326                         channel_id: chan.2,
3327                         htlc_id: 0,
3328                         amount_msat: 0,
3329                         payment_hash,
3330                         cltv_expiry,
3331                         onion_routing_packet,
3332                 };
3333                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3334         }
3335         let events = nodes[0].node.get_and_clear_pending_events();
3336         assert_eq!(events.len(), 2);
3337         // Check that Alice fails backward the pending HTLC from the second payment.
3338         match events[0] {
3339                 Event::PaymentPathFailed { payment_hash, .. } => {
3340                         assert_eq!(payment_hash, failed_payment_hash);
3341                 },
3342                 _ => panic!("Unexpected event"),
3343         }
3344         match events[1] {
3345                 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3346                         assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3347                 },
3348                 _ => panic!("Unexpected event {:?}", events[1]),
3349         }
3350         check_closed_broadcast!(nodes[0], true);
3351         check_added_monitors!(nodes[0], 1);
3352 }
3353
3354 #[test]
3355 fn test_htlc_ignore_latest_remote_commitment() {
3356         // Test that HTLC transactions spending the latest remote commitment transaction are simply
3357         // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3358         let chanmon_cfgs = create_chanmon_cfgs(2);
3359         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3360         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3361         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3362         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3363
3364         route_payment(&nodes[0], &[&nodes[1]], 10000000);
3365         nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id).unwrap();
3366         connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3367         check_closed_broadcast!(nodes[0], true);
3368         check_added_monitors!(nodes[0], 1);
3369         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
3370
3371         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3372         assert_eq!(node_txn.len(), 3);
3373         assert_eq!(node_txn[0], node_txn[1]);
3374
3375         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3376         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3377         check_closed_broadcast!(nodes[1], true);
3378         check_added_monitors!(nodes[1], 1);
3379         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3380
3381         // Duplicate the connect_block call since this may happen due to other listeners
3382         // registering new transactions
3383         header.prev_blockhash = header.block_hash();
3384         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[2].clone()]});
3385 }
3386
3387 #[test]
3388 fn test_force_close_fail_back() {
3389         // Check which HTLCs are failed-backwards on channel force-closure
3390         let chanmon_cfgs = create_chanmon_cfgs(3);
3391         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3392         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3393         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3394         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3395         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3396
3397         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3398
3399         let mut payment_event = {
3400                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
3401                 check_added_monitors!(nodes[0], 1);
3402
3403                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3404                 assert_eq!(events.len(), 1);
3405                 SendEvent::from_event(events.remove(0))
3406         };
3407
3408         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3409         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3410
3411         expect_pending_htlcs_forwardable!(nodes[1]);
3412
3413         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3414         assert_eq!(events_2.len(), 1);
3415         payment_event = SendEvent::from_event(events_2.remove(0));
3416         assert_eq!(payment_event.msgs.len(), 1);
3417
3418         check_added_monitors!(nodes[1], 1);
3419         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3420         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3421         check_added_monitors!(nodes[2], 1);
3422         let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3423
3424         // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3425         // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3426         // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3427
3428         nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id).unwrap();
3429         check_closed_broadcast!(nodes[2], true);
3430         check_added_monitors!(nodes[2], 1);
3431         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
3432         let tx = {
3433                 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3434                 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3435                 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3436                 // back to nodes[1] upon timeout otherwise.
3437                 assert_eq!(node_txn.len(), 1);
3438                 node_txn.remove(0)
3439         };
3440
3441         mine_transaction(&nodes[1], &tx);
3442
3443         // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3444         check_closed_broadcast!(nodes[1], true);
3445         check_added_monitors!(nodes[1], 1);
3446         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3447
3448         // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3449         {
3450                 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3451                         .provide_payment_preimage(&our_payment_hash, &our_payment_preimage, &node_cfgs[2].tx_broadcaster, &node_cfgs[2].fee_estimator, &node_cfgs[2].logger);
3452         }
3453         mine_transaction(&nodes[2], &tx);
3454         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3455         assert_eq!(node_txn.len(), 1);
3456         assert_eq!(node_txn[0].input.len(), 1);
3457         assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3458         assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3459         assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3460
3461         check_spends!(node_txn[0], tx);
3462 }
3463
3464 #[test]
3465 fn test_dup_events_on_peer_disconnect() {
3466         // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3467         // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3468         // as we used to generate the event immediately upon receipt of the payment preimage in the
3469         // update_fulfill_htlc message.
3470
3471         let chanmon_cfgs = create_chanmon_cfgs(2);
3472         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3473         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3474         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3475         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3476
3477         let payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 1000000).0;
3478
3479         assert!(nodes[1].node.claim_funds(payment_preimage));
3480         check_added_monitors!(nodes[1], 1);
3481         let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3482         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3483         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
3484
3485         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3486         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3487
3488         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3489         expect_payment_path_successful!(nodes[0]);
3490 }
3491
3492 #[test]
3493 fn test_simple_peer_disconnect() {
3494         // Test that we can reconnect when there are no lost messages
3495         let chanmon_cfgs = create_chanmon_cfgs(3);
3496         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3497         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3498         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3499         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3500         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3501
3502         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3503         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3504         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3505
3506         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3507         let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3508         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3509         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3510
3511         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3512         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3513         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3514
3515         let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3516         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3517         let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3518         let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3519
3520         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3521         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3522
3523         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3524         fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3525
3526         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3527         {
3528                 let events = nodes[0].node.get_and_clear_pending_events();
3529                 assert_eq!(events.len(), 3);
3530                 match events[0] {
3531                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3532                                 assert_eq!(payment_preimage, payment_preimage_3);
3533                                 assert_eq!(payment_hash, payment_hash_3);
3534                         },
3535                         _ => panic!("Unexpected event"),
3536                 }
3537                 match events[1] {
3538                         Event::PaymentPathFailed { payment_hash, rejected_by_dest, .. } => {
3539                                 assert_eq!(payment_hash, payment_hash_5);
3540                                 assert!(rejected_by_dest);
3541                         },
3542                         _ => panic!("Unexpected event"),
3543                 }
3544                 match events[2] {
3545                         Event::PaymentPathSuccessful { .. } => {},
3546                         _ => panic!("Unexpected event"),
3547                 }
3548         }
3549
3550         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3551         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3552 }
3553
3554 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3555         // Test that we can reconnect when in-flight HTLC updates get dropped
3556         let chanmon_cfgs = create_chanmon_cfgs(2);
3557         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3558         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3559         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3560
3561         let mut as_funding_locked = None;
3562         if messages_delivered == 0 {
3563                 let (funding_locked, _, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3564                 as_funding_locked = Some(funding_locked);
3565                 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
3566                 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3567                 // it before the channel_reestablish message.
3568         } else {
3569                 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3570         }
3571
3572         let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3573
3574         let payment_event = {
3575                 nodes[0].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)).unwrap();
3576                 check_added_monitors!(nodes[0], 1);
3577
3578                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3579                 assert_eq!(events.len(), 1);
3580                 SendEvent::from_event(events.remove(0))
3581         };
3582         assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3583
3584         if messages_delivered < 2 {
3585                 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3586         } else {
3587                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3588                 if messages_delivered >= 3 {
3589                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3590                         check_added_monitors!(nodes[1], 1);
3591                         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3592
3593                         if messages_delivered >= 4 {
3594                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3595                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3596                                 check_added_monitors!(nodes[0], 1);
3597
3598                                 if messages_delivered >= 5 {
3599                                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3600                                         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3601                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3602                                         check_added_monitors!(nodes[0], 1);
3603
3604                                         if messages_delivered >= 6 {
3605                                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3606                                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3607                                                 check_added_monitors!(nodes[1], 1);
3608                                         }
3609                                 }
3610                         }
3611                 }
3612         }
3613
3614         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3615         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3616         if messages_delivered < 3 {
3617                 if simulate_broken_lnd {
3618                         // lnd has a long-standing bug where they send a funding_locked prior to a
3619                         // channel_reestablish if you reconnect prior to funding_locked time.
3620                         //
3621                         // Here we simulate that behavior, delivering a funding_locked immediately on
3622                         // reconnect. Note that we don't bother skipping the now-duplicate funding_locked sent
3623                         // in `reconnect_nodes` but we currently don't fail based on that.
3624                         //
3625                         // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3626                         nodes[1].node.handle_funding_locked(&nodes[0].node.get_our_node_id(), &as_funding_locked.as_ref().unwrap().0);
3627                 }
3628                 // Even if the funding_locked messages get exchanged, as long as nothing further was
3629                 // received on either side, both sides will need to resend them.
3630                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3631         } else if messages_delivered == 3 {
3632                 // nodes[0] still wants its RAA + commitment_signed
3633                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3634         } else if messages_delivered == 4 {
3635                 // nodes[0] still wants its commitment_signed
3636                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3637         } else if messages_delivered == 5 {
3638                 // nodes[1] still wants its final RAA
3639                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3640         } else if messages_delivered == 6 {
3641                 // Everything was delivered...
3642                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3643         }
3644
3645         let events_1 = nodes[1].node.get_and_clear_pending_events();
3646         assert_eq!(events_1.len(), 1);
3647         match events_1[0] {
3648                 Event::PendingHTLCsForwardable { .. } => { },
3649                 _ => panic!("Unexpected event"),
3650         };
3651
3652         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3653         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3654         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3655
3656         nodes[1].node.process_pending_htlc_forwards();
3657
3658         let events_2 = nodes[1].node.get_and_clear_pending_events();
3659         assert_eq!(events_2.len(), 1);
3660         match events_2[0] {
3661                 Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
3662                         assert_eq!(payment_hash_1, *payment_hash);
3663                         assert_eq!(amt, 1000000);
3664                         match &purpose {
3665                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3666                                         assert!(payment_preimage.is_none());
3667                                         assert_eq!(payment_secret_1, *payment_secret);
3668                                 },
3669                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
3670                         }
3671                 },
3672                 _ => panic!("Unexpected event"),
3673         }
3674
3675         nodes[1].node.claim_funds(payment_preimage_1);
3676         check_added_monitors!(nodes[1], 1);
3677
3678         let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3679         assert_eq!(events_3.len(), 1);
3680         let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3681                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3682                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3683                         assert!(updates.update_add_htlcs.is_empty());
3684                         assert!(updates.update_fail_htlcs.is_empty());
3685                         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3686                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3687                         assert!(updates.update_fee.is_none());
3688                         (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3689                 },
3690                 _ => panic!("Unexpected event"),
3691         };
3692
3693         if messages_delivered >= 1 {
3694                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3695
3696                 let events_4 = nodes[0].node.get_and_clear_pending_events();
3697                 assert_eq!(events_4.len(), 1);
3698                 match events_4[0] {
3699                         Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3700                                 assert_eq!(payment_preimage_1, *payment_preimage);
3701                                 assert_eq!(payment_hash_1, *payment_hash);
3702                         },
3703                         _ => panic!("Unexpected event"),
3704                 }
3705
3706                 if messages_delivered >= 2 {
3707                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3708                         check_added_monitors!(nodes[0], 1);
3709                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3710
3711                         if messages_delivered >= 3 {
3712                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3713                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3714                                 check_added_monitors!(nodes[1], 1);
3715
3716                                 if messages_delivered >= 4 {
3717                                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3718                                         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3719                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3720                                         check_added_monitors!(nodes[1], 1);
3721
3722                                         if messages_delivered >= 5 {
3723                                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3724                                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3725                                                 check_added_monitors!(nodes[0], 1);
3726                                         }
3727                                 }
3728                         }
3729                 }
3730         }
3731
3732         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3733         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3734         if messages_delivered < 2 {
3735                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3736                 if messages_delivered < 1 {
3737                         expect_payment_sent!(nodes[0], payment_preimage_1);
3738                 } else {
3739                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3740                 }
3741         } else if messages_delivered == 2 {
3742                 // nodes[0] still wants its RAA + commitment_signed
3743                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3744         } else if messages_delivered == 3 {
3745                 // nodes[0] still wants its commitment_signed
3746                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3747         } else if messages_delivered == 4 {
3748                 // nodes[1] still wants its final RAA
3749                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3750         } else if messages_delivered == 5 {
3751                 // Everything was delivered...
3752                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3753         }
3754
3755         if messages_delivered == 1 || messages_delivered == 2 {
3756                 expect_payment_path_successful!(nodes[0]);
3757         }
3758
3759         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3760         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3761         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3762
3763         if messages_delivered > 2 {
3764                 expect_payment_path_successful!(nodes[0]);
3765         }
3766
3767         // Channel should still work fine...
3768         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3769         let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3770         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3771 }
3772
3773 #[test]
3774 fn test_drop_messages_peer_disconnect_a() {
3775         do_test_drop_messages_peer_disconnect(0, true);
3776         do_test_drop_messages_peer_disconnect(0, false);
3777         do_test_drop_messages_peer_disconnect(1, false);
3778         do_test_drop_messages_peer_disconnect(2, false);
3779 }
3780
3781 #[test]
3782 fn test_drop_messages_peer_disconnect_b() {
3783         do_test_drop_messages_peer_disconnect(3, false);
3784         do_test_drop_messages_peer_disconnect(4, false);
3785         do_test_drop_messages_peer_disconnect(5, false);
3786         do_test_drop_messages_peer_disconnect(6, false);
3787 }
3788
3789 #[test]
3790 fn test_funding_peer_disconnect() {
3791         // Test that we can lock in our funding tx while disconnected
3792         let chanmon_cfgs = create_chanmon_cfgs(2);
3793         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3794         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3795         let persister: test_utils::TestPersister;
3796         let new_chain_monitor: test_utils::TestChainMonitor;
3797         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
3798         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3799         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3800
3801         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3802         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3803
3804         confirm_transaction(&nodes[0], &tx);
3805         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3806         assert!(events_1.is_empty());
3807
3808         reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3809
3810         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3811         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3812
3813         confirm_transaction(&nodes[1], &tx);
3814         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3815         assert!(events_2.is_empty());
3816
3817         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
3818         let as_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
3819         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
3820         let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
3821
3822         // nodes[0] hasn't yet received a funding_locked, so it only sends that on reconnect.
3823         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
3824         let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3825         assert_eq!(events_3.len(), 1);
3826         let as_funding_locked = match events_3[0] {
3827                 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3828                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3829                         msg.clone()
3830                 },
3831                 _ => panic!("Unexpected event {:?}", events_3[0]),
3832         };
3833
3834         // nodes[1] received nodes[0]'s funding_locked on the first reconnect above, so it should send
3835         // announcement_signatures as well as channel_update.
3836         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reestablish);
3837         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3838         assert_eq!(events_4.len(), 3);
3839         let chan_id;
3840         let bs_funding_locked = match events_4[0] {
3841                 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3842                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3843                         chan_id = msg.channel_id;
3844                         msg.clone()
3845                 },
3846                 _ => panic!("Unexpected event {:?}", events_4[0]),
3847         };
3848         let bs_announcement_sigs = match events_4[1] {
3849                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3850                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3851                         msg.clone()
3852                 },
3853                 _ => panic!("Unexpected event {:?}", events_4[1]),
3854         };
3855         match events_4[2] {
3856                 MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } => {
3857                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3858                 },
3859                 _ => panic!("Unexpected event {:?}", events_4[2]),
3860         }
3861
3862         // Re-deliver nodes[0]'s funding_locked, which nodes[1] can safely ignore. It currently
3863         // generates a duplicative private channel_update
3864         nodes[1].node.handle_funding_locked(&nodes[0].node.get_our_node_id(), &as_funding_locked);
3865         let events_5 = nodes[1].node.get_and_clear_pending_msg_events();
3866         assert_eq!(events_5.len(), 1);
3867         match events_5[0] {
3868                 MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } => {
3869                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3870                 },
3871                 _ => panic!("Unexpected event {:?}", events_5[0]),
3872         };
3873
3874         // When we deliver nodes[1]'s funding_locked, however, nodes[0] will generate its
3875         // announcement_signatures.
3876         nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &bs_funding_locked);
3877         let events_6 = nodes[0].node.get_and_clear_pending_msg_events();
3878         assert_eq!(events_6.len(), 1);
3879         let as_announcement_sigs = match events_6[0] {
3880                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3881                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3882                         msg.clone()
3883                 },
3884                 _ => panic!("Unexpected event {:?}", events_6[0]),
3885         };
3886
3887         // When we deliver nodes[1]'s announcement_signatures to nodes[0], nodes[0] should immediately
3888         // broadcast the channel announcement globally, as well as re-send its (now-public)
3889         // channel_update.
3890         nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3891         let events_7 = nodes[0].node.get_and_clear_pending_msg_events();
3892         assert_eq!(events_7.len(), 1);
3893         let (chan_announcement, as_update) = match events_7[0] {
3894                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3895                         (msg.clone(), update_msg.clone())
3896                 },
3897                 _ => panic!("Unexpected event {:?}", events_7[0]),
3898         };
3899
3900         // Finally, deliver nodes[0]'s announcement_signatures to nodes[1] and make sure it creates the
3901         // same channel_announcement.
3902         nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3903         let events_8 = nodes[1].node.get_and_clear_pending_msg_events();
3904         assert_eq!(events_8.len(), 1);
3905         let bs_update = match events_8[0] {
3906                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3907                         assert_eq!(*msg, chan_announcement);
3908                         update_msg.clone()
3909                 },
3910                 _ => panic!("Unexpected event {:?}", events_8[0]),
3911         };
3912
3913         // Provide the channel announcement and public updates to the network graph
3914         nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).unwrap();
3915         nodes[0].net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
3916         nodes[0].net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
3917
3918         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3919         let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3920         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
3921
3922         // Check that after deserialization and reconnection we can still generate an identical
3923         // channel_announcement from the cached signatures.
3924         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3925
3926         let nodes_0_serialized = nodes[0].node.encode();
3927         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
3928         get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
3929
3930         persister = test_utils::TestPersister::new();
3931         let keys_manager = &chanmon_cfgs[0].keys_manager;
3932         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);
3933         nodes[0].chain_monitor = &new_chain_monitor;
3934         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
3935         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
3936                 &mut chan_0_monitor_read, keys_manager).unwrap();
3937         assert!(chan_0_monitor_read.is_empty());
3938
3939         let mut nodes_0_read = &nodes_0_serialized[..];
3940         let (_, nodes_0_deserialized_tmp) = {
3941                 let mut channel_monitors = HashMap::new();
3942                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
3943                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
3944                         default_config: UserConfig::default(),
3945                         keys_manager,
3946                         fee_estimator: node_cfgs[0].fee_estimator,
3947                         chain_monitor: nodes[0].chain_monitor,
3948                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
3949                         logger: nodes[0].logger,
3950                         channel_monitors,
3951                 }).unwrap()
3952         };
3953         nodes_0_deserialized = nodes_0_deserialized_tmp;
3954         assert!(nodes_0_read.is_empty());
3955
3956         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
3957         nodes[0].node = &nodes_0_deserialized;
3958         check_added_monitors!(nodes[0], 1);
3959
3960         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3961
3962         // The channel announcement should be re-generated exactly by broadcast_node_announcement.
3963         nodes[0].node.broadcast_node_announcement([0, 0, 0], [0; 32], Vec::new());
3964         let msgs = nodes[0].node.get_and_clear_pending_msg_events();
3965         let mut found_announcement = false;
3966         for event in msgs.iter() {
3967                 match event {
3968                         MessageSendEvent::BroadcastChannelAnnouncement { ref msg, .. } => {
3969                                 if *msg == chan_announcement { found_announcement = true; }
3970                         },
3971                         MessageSendEvent::BroadcastNodeAnnouncement { .. } => {},
3972                         _ => panic!("Unexpected event"),
3973                 }
3974         }
3975         assert!(found_announcement);
3976 }
3977
3978 #[test]
3979 fn test_funding_locked_without_best_block_updated() {
3980         // Previously, if we were offline when a funding transaction was locked in, and then we came
3981         // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
3982         // generate a funding_locked until a later best_block_updated. This tests that we generate the
3983         // funding_locked immediately instead.
3984         let chanmon_cfgs = create_chanmon_cfgs(2);
3985         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3986         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3987         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3988         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
3989
3990         let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
3991
3992         let conf_height = nodes[0].best_block_info().1 + 1;
3993         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
3994         let block_txn = [funding_tx];
3995         let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
3996         let conf_block_header = nodes[0].get_block_header(conf_height);
3997         nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
3998
3999         // Ensure nodes[0] generates a funding_locked after the transactions_confirmed
4000         let as_funding_locked = get_event_msg!(nodes[0], MessageSendEvent::SendFundingLocked, nodes[1].node.get_our_node_id());
4001         nodes[1].node.handle_funding_locked(&nodes[0].node.get_our_node_id(), &as_funding_locked);
4002 }
4003
4004 #[test]
4005 fn test_drop_messages_peer_disconnect_dual_htlc() {
4006         // Test that we can handle reconnecting when both sides of a channel have pending
4007         // commitment_updates when we disconnect.
4008         let chanmon_cfgs = create_chanmon_cfgs(2);
4009         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4010         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4011         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4012         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4013
4014         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4015
4016         // Now try to send a second payment which will fail to send
4017         let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
4018         nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
4019         check_added_monitors!(nodes[0], 1);
4020
4021         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
4022         assert_eq!(events_1.len(), 1);
4023         match events_1[0] {
4024                 MessageSendEvent::UpdateHTLCs { .. } => {},
4025                 _ => panic!("Unexpected event"),
4026         }
4027
4028         assert!(nodes[1].node.claim_funds(payment_preimage_1));
4029         check_added_monitors!(nodes[1], 1);
4030
4031         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
4032         assert_eq!(events_2.len(), 1);
4033         match events_2[0] {
4034                 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 } } => {
4035                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
4036                         assert!(update_add_htlcs.is_empty());
4037                         assert_eq!(update_fulfill_htlcs.len(), 1);
4038                         assert!(update_fail_htlcs.is_empty());
4039                         assert!(update_fail_malformed_htlcs.is_empty());
4040                         assert!(update_fee.is_none());
4041
4042                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
4043                         let events_3 = nodes[0].node.get_and_clear_pending_events();
4044                         assert_eq!(events_3.len(), 1);
4045                         match events_3[0] {
4046                                 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4047                                         assert_eq!(*payment_preimage, payment_preimage_1);
4048                                         assert_eq!(*payment_hash, payment_hash_1);
4049                                 },
4050                                 _ => panic!("Unexpected event"),
4051                         }
4052
4053                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
4054                         let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4055                         // No commitment_signed so get_event_msg's assert(len == 1) passes
4056                         check_added_monitors!(nodes[0], 1);
4057                 },
4058                 _ => panic!("Unexpected event"),
4059         }
4060
4061         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
4062         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4063
4064         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4065         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4066         assert_eq!(reestablish_1.len(), 1);
4067         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4068         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4069         assert_eq!(reestablish_2.len(), 1);
4070
4071         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4072         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4073         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4074         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4075
4076         assert!(as_resp.0.is_none());
4077         assert!(bs_resp.0.is_none());
4078
4079         assert!(bs_resp.1.is_none());
4080         assert!(bs_resp.2.is_none());
4081
4082         assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4083
4084         assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4085         assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4086         assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4087         assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4088         assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4089         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4090         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4091         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4092         // No commitment_signed so get_event_msg's assert(len == 1) passes
4093         check_added_monitors!(nodes[1], 1);
4094
4095         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4096         let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4097         assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4098         assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4099         assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4100         assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4101         assert!(bs_second_commitment_signed.update_fee.is_none());
4102         check_added_monitors!(nodes[1], 1);
4103
4104         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4105         let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4106         assert!(as_commitment_signed.update_add_htlcs.is_empty());
4107         assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4108         assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4109         assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4110         assert!(as_commitment_signed.update_fee.is_none());
4111         check_added_monitors!(nodes[0], 1);
4112
4113         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4114         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4115         // No commitment_signed so get_event_msg's assert(len == 1) passes
4116         check_added_monitors!(nodes[0], 1);
4117
4118         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4119         let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4120         // No commitment_signed so get_event_msg's assert(len == 1) passes
4121         check_added_monitors!(nodes[1], 1);
4122
4123         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4124         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4125         check_added_monitors!(nodes[1], 1);
4126
4127         expect_pending_htlcs_forwardable!(nodes[1]);
4128
4129         let events_5 = nodes[1].node.get_and_clear_pending_events();
4130         assert_eq!(events_5.len(), 1);
4131         match events_5[0] {
4132                 Event::PaymentReceived { ref payment_hash, ref purpose, .. } => {
4133                         assert_eq!(payment_hash_2, *payment_hash);
4134                         match &purpose {
4135                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4136                                         assert!(payment_preimage.is_none());
4137                                         assert_eq!(payment_secret_2, *payment_secret);
4138                                 },
4139                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
4140                         }
4141                 },
4142                 _ => panic!("Unexpected event"),
4143         }
4144
4145         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4146         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4147         check_added_monitors!(nodes[0], 1);
4148
4149         expect_payment_path_successful!(nodes[0]);
4150         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4151 }
4152
4153 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4154         // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4155         // to avoid our counterparty failing the channel.
4156         let chanmon_cfgs = create_chanmon_cfgs(2);
4157         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4158         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4159         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4160
4161         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4162
4163         let our_payment_hash = if send_partial_mpp {
4164                 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4165                 // Use the utility function send_payment_along_path to send the payment with MPP data which
4166                 // indicates there are more HTLCs coming.
4167                 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.
4168                 let payment_id = PaymentId([42; 32]);
4169                 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();
4170                 check_added_monitors!(nodes[0], 1);
4171                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4172                 assert_eq!(events.len(), 1);
4173                 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4174                 // hop should *not* yet generate any PaymentReceived event(s).
4175                 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4176                 our_payment_hash
4177         } else {
4178                 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4179         };
4180
4181         let mut block = Block {
4182                 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
4183                 txdata: vec![],
4184         };
4185         connect_block(&nodes[0], &block);
4186         connect_block(&nodes[1], &block);
4187         let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4188         for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4189                 block.header.prev_blockhash = block.block_hash();
4190                 connect_block(&nodes[0], &block);
4191                 connect_block(&nodes[1], &block);
4192         }
4193
4194         expect_pending_htlcs_forwardable!(nodes[1]);
4195
4196         check_added_monitors!(nodes[1], 1);
4197         let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4198         assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4199         assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4200         assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4201         assert!(htlc_timeout_updates.update_fee.is_none());
4202
4203         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4204         commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4205         // 100_000 msat as u64, followed by the height at which we failed back above
4206         let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
4207         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(block_count - 1));
4208         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4209 }
4210
4211 #[test]
4212 fn test_htlc_timeout() {
4213         do_test_htlc_timeout(true);
4214         do_test_htlc_timeout(false);
4215 }
4216
4217 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4218         // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4219         let chanmon_cfgs = create_chanmon_cfgs(3);
4220         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4221         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4222         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4223         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4224         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4225
4226         // Make sure all nodes are at the same starting height
4227         connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4228         connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4229         connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4230
4231         // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4232         let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4233         {
4234                 nodes[1].node.send_payment(&route, first_payment_hash, &Some(first_payment_secret)).unwrap();
4235         }
4236         assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4237         check_added_monitors!(nodes[1], 1);
4238
4239         // Now attempt to route a second payment, which should be placed in the holding cell
4240         let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4241         let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4242         sending_node.node.send_payment(&route, second_payment_hash, &Some(second_payment_secret)).unwrap();
4243         if forwarded_htlc {
4244                 check_added_monitors!(nodes[0], 1);
4245                 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4246                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4247                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4248                 expect_pending_htlcs_forwardable!(nodes[1]);
4249         }
4250         check_added_monitors!(nodes[1], 0);
4251
4252         connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4253         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4254         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4255         connect_blocks(&nodes[1], 1);
4256
4257         if forwarded_htlc {
4258                 expect_pending_htlcs_forwardable!(nodes[1]);
4259                 check_added_monitors!(nodes[1], 1);
4260                 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4261                 assert_eq!(fail_commit.len(), 1);
4262                 match fail_commit[0] {
4263                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4264                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4265                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4266                         },
4267                         _ => unreachable!(),
4268                 }
4269                 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4270         } else {
4271                 let events = nodes[1].node.get_and_clear_pending_events();
4272                 assert_eq!(events.len(), 2);
4273                 if let Event::PaymentPathFailed { ref payment_hash, .. } = events[0] {
4274                         assert_eq!(*payment_hash, second_payment_hash);
4275                 } else { panic!("Unexpected event"); }
4276                 if let Event::PaymentFailed { ref payment_hash, .. } = events[1] {
4277                         assert_eq!(*payment_hash, second_payment_hash);
4278                 } else { panic!("Unexpected event"); }
4279         }
4280 }
4281
4282 #[test]
4283 fn test_holding_cell_htlc_add_timeouts() {
4284         do_test_holding_cell_htlc_add_timeouts(false);
4285         do_test_holding_cell_htlc_add_timeouts(true);
4286 }
4287
4288 #[test]
4289 fn test_no_txn_manager_serialize_deserialize() {
4290         let chanmon_cfgs = create_chanmon_cfgs(2);
4291         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4292         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4293         let logger: test_utils::TestLogger;
4294         let fee_estimator: test_utils::TestFeeEstimator;
4295         let persister: test_utils::TestPersister;
4296         let new_chain_monitor: test_utils::TestChainMonitor;
4297         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4298         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4299
4300         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
4301
4302         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4303
4304         let nodes_0_serialized = nodes[0].node.encode();
4305         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4306         get_monitor!(nodes[0], OutPoint { txid: tx.txid(), index: 0 }.to_channel_id())
4307                 .write(&mut chan_0_monitor_serialized).unwrap();
4308
4309         logger = test_utils::TestLogger::new();
4310         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4311         persister = test_utils::TestPersister::new();
4312         let keys_manager = &chanmon_cfgs[0].keys_manager;
4313         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4314         nodes[0].chain_monitor = &new_chain_monitor;
4315         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4316         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4317                 &mut chan_0_monitor_read, keys_manager).unwrap();
4318         assert!(chan_0_monitor_read.is_empty());
4319
4320         let mut nodes_0_read = &nodes_0_serialized[..];
4321         let config = UserConfig::default();
4322         let (_, nodes_0_deserialized_tmp) = {
4323                 let mut channel_monitors = HashMap::new();
4324                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4325                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4326                         default_config: config,
4327                         keys_manager,
4328                         fee_estimator: &fee_estimator,
4329                         chain_monitor: nodes[0].chain_monitor,
4330                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4331                         logger: &logger,
4332                         channel_monitors,
4333                 }).unwrap()
4334         };
4335         nodes_0_deserialized = nodes_0_deserialized_tmp;
4336         assert!(nodes_0_read.is_empty());
4337
4338         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4339         nodes[0].node = &nodes_0_deserialized;
4340         assert_eq!(nodes[0].node.list_channels().len(), 1);
4341         check_added_monitors!(nodes[0], 1);
4342
4343         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4344         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4345         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4346         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4347
4348         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4349         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4350         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4351         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4352
4353         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4354         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4355         for node in nodes.iter() {
4356                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4357                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4358                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4359         }
4360
4361         send_payment(&nodes[0], &[&nodes[1]], 1000000);
4362 }
4363
4364 #[test]
4365 fn test_manager_serialize_deserialize_events() {
4366         // This test makes sure the events field in ChannelManager survives de/serialization
4367         let chanmon_cfgs = create_chanmon_cfgs(2);
4368         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4369         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4370         let fee_estimator: test_utils::TestFeeEstimator;
4371         let persister: test_utils::TestPersister;
4372         let logger: test_utils::TestLogger;
4373         let new_chain_monitor: test_utils::TestChainMonitor;
4374         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4375         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4376
4377         // Start creating a channel, but stop right before broadcasting the funding transaction
4378         let channel_value = 100000;
4379         let push_msat = 10001;
4380         let a_flags = InitFeatures::known();
4381         let b_flags = InitFeatures::known();
4382         let node_a = nodes.remove(0);
4383         let node_b = nodes.remove(0);
4384         node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
4385         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()));
4386         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()));
4387
4388         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, channel_value, 42);
4389
4390         node_a.node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
4391         check_added_monitors!(node_a, 0);
4392
4393         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()));
4394         {
4395                 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
4396                 assert_eq!(added_monitors.len(), 1);
4397                 assert_eq!(added_monitors[0].0, funding_output);
4398                 added_monitors.clear();
4399         }
4400
4401         let bs_funding_signed = get_event_msg!(node_b, MessageSendEvent::SendFundingSigned, node_a.node.get_our_node_id());
4402         node_a.node.handle_funding_signed(&node_b.node.get_our_node_id(), &bs_funding_signed);
4403         {
4404                 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
4405                 assert_eq!(added_monitors.len(), 1);
4406                 assert_eq!(added_monitors[0].0, funding_output);
4407                 added_monitors.clear();
4408         }
4409         // Normally, this is where node_a would broadcast the funding transaction, but the test de/serializes first instead
4410
4411         nodes.push(node_a);
4412         nodes.push(node_b);
4413
4414         // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4415         let nodes_0_serialized = nodes[0].node.encode();
4416         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4417         get_monitor!(nodes[0], bs_funding_signed.channel_id).write(&mut chan_0_monitor_serialized).unwrap();
4418
4419         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4420         logger = test_utils::TestLogger::new();
4421         persister = test_utils::TestPersister::new();
4422         let keys_manager = &chanmon_cfgs[0].keys_manager;
4423         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4424         nodes[0].chain_monitor = &new_chain_monitor;
4425         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4426         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4427                 &mut chan_0_monitor_read, keys_manager).unwrap();
4428         assert!(chan_0_monitor_read.is_empty());
4429
4430         let mut nodes_0_read = &nodes_0_serialized[..];
4431         let config = UserConfig::default();
4432         let (_, nodes_0_deserialized_tmp) = {
4433                 let mut channel_monitors = HashMap::new();
4434                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4435                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4436                         default_config: config,
4437                         keys_manager,
4438                         fee_estimator: &fee_estimator,
4439                         chain_monitor: nodes[0].chain_monitor,
4440                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4441                         logger: &logger,
4442                         channel_monitors,
4443                 }).unwrap()
4444         };
4445         nodes_0_deserialized = nodes_0_deserialized_tmp;
4446         assert!(nodes_0_read.is_empty());
4447
4448         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4449
4450         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4451         nodes[0].node = &nodes_0_deserialized;
4452
4453         // After deserializing, make sure the funding_transaction is still held by the channel manager
4454         let events_4 = nodes[0].node.get_and_clear_pending_events();
4455         assert_eq!(events_4.len(), 0);
4456         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
4457         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
4458
4459         // Make sure the channel is functioning as though the de/serialization never happened
4460         assert_eq!(nodes[0].node.list_channels().len(), 1);
4461         check_added_monitors!(nodes[0], 1);
4462
4463         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4464         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4465         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4466         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4467
4468         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4469         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4470         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4471         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4472
4473         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4474         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4475         for node in nodes.iter() {
4476                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4477                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4478                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4479         }
4480
4481         send_payment(&nodes[0], &[&nodes[1]], 1000000);
4482 }
4483
4484 #[test]
4485 fn test_simple_manager_serialize_deserialize() {
4486         let chanmon_cfgs = create_chanmon_cfgs(2);
4487         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4488         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4489         let logger: test_utils::TestLogger;
4490         let fee_estimator: test_utils::TestFeeEstimator;
4491         let persister: test_utils::TestPersister;
4492         let new_chain_monitor: test_utils::TestChainMonitor;
4493         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4494         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4495         let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
4496
4497         let (our_payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4498         let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4499
4500         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4501
4502         let nodes_0_serialized = nodes[0].node.encode();
4503         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4504         get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
4505
4506         logger = test_utils::TestLogger::new();
4507         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4508         persister = test_utils::TestPersister::new();
4509         let keys_manager = &chanmon_cfgs[0].keys_manager;
4510         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4511         nodes[0].chain_monitor = &new_chain_monitor;
4512         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4513         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4514                 &mut chan_0_monitor_read, keys_manager).unwrap();
4515         assert!(chan_0_monitor_read.is_empty());
4516
4517         let mut nodes_0_read = &nodes_0_serialized[..];
4518         let (_, nodes_0_deserialized_tmp) = {
4519                 let mut channel_monitors = HashMap::new();
4520                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4521                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4522                         default_config: UserConfig::default(),
4523                         keys_manager,
4524                         fee_estimator: &fee_estimator,
4525                         chain_monitor: nodes[0].chain_monitor,
4526                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4527                         logger: &logger,
4528                         channel_monitors,
4529                 }).unwrap()
4530         };
4531         nodes_0_deserialized = nodes_0_deserialized_tmp;
4532         assert!(nodes_0_read.is_empty());
4533
4534         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4535         nodes[0].node = &nodes_0_deserialized;
4536         check_added_monitors!(nodes[0], 1);
4537
4538         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4539
4540         fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4541         claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
4542 }
4543
4544 #[test]
4545 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4546         // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4547         let chanmon_cfgs = create_chanmon_cfgs(4);
4548         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4549         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4550         let logger: test_utils::TestLogger;
4551         let fee_estimator: test_utils::TestFeeEstimator;
4552         let persister: test_utils::TestPersister;
4553         let new_chain_monitor: test_utils::TestChainMonitor;
4554         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4555         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4556         let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
4557         let chan_id_2 = create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known()).2;
4558         let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
4559
4560         let mut node_0_stale_monitors_serialized = Vec::new();
4561         for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4562                 let mut writer = test_utils::TestVecWriter(Vec::new());
4563                 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4564                 node_0_stale_monitors_serialized.push(writer.0);
4565         }
4566
4567         let (our_payment_preimage, _, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4568
4569         // Serialize the ChannelManager here, but the monitor we keep up-to-date
4570         let nodes_0_serialized = nodes[0].node.encode();
4571
4572         route_payment(&nodes[0], &[&nodes[3]], 1000000);
4573         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4574         nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4575         nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4576
4577         // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4578         // nodes[3])
4579         let mut node_0_monitors_serialized = Vec::new();
4580         for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4581                 let mut writer = test_utils::TestVecWriter(Vec::new());
4582                 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4583                 node_0_monitors_serialized.push(writer.0);
4584         }
4585
4586         logger = test_utils::TestLogger::new();
4587         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4588         persister = test_utils::TestPersister::new();
4589         let keys_manager = &chanmon_cfgs[0].keys_manager;
4590         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4591         nodes[0].chain_monitor = &new_chain_monitor;
4592
4593
4594         let mut node_0_stale_monitors = Vec::new();
4595         for serialized in node_0_stale_monitors_serialized.iter() {
4596                 let mut read = &serialized[..];
4597                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4598                 assert!(read.is_empty());
4599                 node_0_stale_monitors.push(monitor);
4600         }
4601
4602         let mut node_0_monitors = Vec::new();
4603         for serialized in node_0_monitors_serialized.iter() {
4604                 let mut read = &serialized[..];
4605                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4606                 assert!(read.is_empty());
4607                 node_0_monitors.push(monitor);
4608         }
4609
4610         let mut nodes_0_read = &nodes_0_serialized[..];
4611         if let Err(msgs::DecodeError::InvalidValue) =
4612                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4613                 default_config: UserConfig::default(),
4614                 keys_manager,
4615                 fee_estimator: &fee_estimator,
4616                 chain_monitor: nodes[0].chain_monitor,
4617                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4618                 logger: &logger,
4619                 channel_monitors: node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4620         }) { } else {
4621                 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4622         };
4623
4624         let mut nodes_0_read = &nodes_0_serialized[..];
4625         let (_, nodes_0_deserialized_tmp) =
4626                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4627                 default_config: UserConfig::default(),
4628                 keys_manager,
4629                 fee_estimator: &fee_estimator,
4630                 chain_monitor: nodes[0].chain_monitor,
4631                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4632                 logger: &logger,
4633                 channel_monitors: node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4634         }).unwrap();
4635         nodes_0_deserialized = nodes_0_deserialized_tmp;
4636         assert!(nodes_0_read.is_empty());
4637
4638         { // Channel close should result in a commitment tx
4639                 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4640                 assert_eq!(txn.len(), 1);
4641                 check_spends!(txn[0], funding_tx);
4642                 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4643         }
4644
4645         for monitor in node_0_monitors.drain(..) {
4646                 assert!(nodes[0].chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor).is_ok());
4647                 check_added_monitors!(nodes[0], 1);
4648         }
4649         nodes[0].node = &nodes_0_deserialized;
4650         check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
4651
4652         // nodes[1] and nodes[2] have no lost state with nodes[0]...
4653         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4654         reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4655         //... and we can even still claim the payment!
4656         claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage);
4657
4658         nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4659         let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4660         nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4661         nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4662         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4663         assert_eq!(msg_events.len(), 1);
4664         if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
4665                 match action {
4666                         &ErrorAction::SendErrorMessage { ref msg } => {
4667                                 assert_eq!(msg.channel_id, channel_id);
4668                         },
4669                         _ => panic!("Unexpected event!"),
4670                 }
4671         }
4672 }
4673
4674 macro_rules! check_spendable_outputs {
4675         ($node: expr, $keysinterface: expr) => {
4676                 {
4677                         let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4678                         let mut txn = Vec::new();
4679                         let mut all_outputs = Vec::new();
4680                         let secp_ctx = Secp256k1::new();
4681                         for event in events.drain(..) {
4682                                 match event {
4683                                         Event::SpendableOutputs { mut outputs } => {
4684                                                 for outp in outputs.drain(..) {
4685                                                         txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4686                                                         all_outputs.push(outp);
4687                                                 }
4688                                         },
4689                                         _ => panic!("Unexpected event"),
4690                                 };
4691                         }
4692                         if all_outputs.len() > 1 {
4693                                 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) {
4694                                         txn.push(tx);
4695                                 }
4696                         }
4697                         txn
4698                 }
4699         }
4700 }
4701
4702 #[test]
4703 fn test_claim_sizeable_push_msat() {
4704         // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4705         let chanmon_cfgs = create_chanmon_cfgs(2);
4706         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4707         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4708         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4709
4710         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000, InitFeatures::known(), InitFeatures::known());
4711         nodes[1].node.force_close_channel(&chan.2).unwrap();
4712         check_closed_broadcast!(nodes[1], true);
4713         check_added_monitors!(nodes[1], 1);
4714         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4715         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4716         assert_eq!(node_txn.len(), 1);
4717         check_spends!(node_txn[0], chan.3);
4718         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
4719
4720         mine_transaction(&nodes[1], &node_txn[0]);
4721         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4722
4723         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4724         assert_eq!(spend_txn.len(), 1);
4725         assert_eq!(spend_txn[0].input.len(), 1);
4726         check_spends!(spend_txn[0], node_txn[0]);
4727         assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
4728 }
4729
4730 #[test]
4731 fn test_claim_on_remote_sizeable_push_msat() {
4732         // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4733         // to_remote output is encumbered by a P2WPKH
4734         let chanmon_cfgs = create_chanmon_cfgs(2);
4735         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4736         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4737         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4738
4739         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000, InitFeatures::known(), InitFeatures::known());
4740         nodes[0].node.force_close_channel(&chan.2).unwrap();
4741         check_closed_broadcast!(nodes[0], true);
4742         check_added_monitors!(nodes[0], 1);
4743         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4744
4745         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4746         assert_eq!(node_txn.len(), 1);
4747         check_spends!(node_txn[0], chan.3);
4748         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
4749
4750         mine_transaction(&nodes[1], &node_txn[0]);
4751         check_closed_broadcast!(nodes[1], true);
4752         check_added_monitors!(nodes[1], 1);
4753         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4754         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4755
4756         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4757         assert_eq!(spend_txn.len(), 1);
4758         check_spends!(spend_txn[0], node_txn[0]);
4759 }
4760
4761 #[test]
4762 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4763         // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4764         // to_remote output is encumbered by a P2WPKH
4765
4766         let chanmon_cfgs = create_chanmon_cfgs(2);
4767         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4768         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4769         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4770
4771         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::known(), InitFeatures::known());
4772         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4773         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4774         assert_eq!(revoked_local_txn[0].input.len(), 1);
4775         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4776
4777         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4778         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4779         check_closed_broadcast!(nodes[1], true);
4780         check_added_monitors!(nodes[1], 1);
4781         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4782
4783         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4784         mine_transaction(&nodes[1], &node_txn[0]);
4785         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4786
4787         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4788         assert_eq!(spend_txn.len(), 3);
4789         check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4790         check_spends!(spend_txn[1], node_txn[0]);
4791         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4792 }
4793
4794 #[test]
4795 fn test_static_spendable_outputs_preimage_tx() {
4796         let chanmon_cfgs = create_chanmon_cfgs(2);
4797         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4798         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4799         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4800
4801         // Create some initial channels
4802         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4803
4804         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4805
4806         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4807         assert_eq!(commitment_tx[0].input.len(), 1);
4808         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4809
4810         // Settle A's commitment tx on B's chain
4811         assert!(nodes[1].node.claim_funds(payment_preimage));
4812         check_added_monitors!(nodes[1], 1);
4813         mine_transaction(&nodes[1], &commitment_tx[0]);
4814         check_added_monitors!(nodes[1], 1);
4815         let events = nodes[1].node.get_and_clear_pending_msg_events();
4816         match events[0] {
4817                 MessageSendEvent::UpdateHTLCs { .. } => {},
4818                 _ => panic!("Unexpected event"),
4819         }
4820         match events[1] {
4821                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4822                 _ => panic!("Unexepected event"),
4823         }
4824
4825         // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4826         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4827         assert_eq!(node_txn.len(), 3);
4828         check_spends!(node_txn[0], commitment_tx[0]);
4829         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4830         check_spends!(node_txn[1], chan_1.3);
4831         check_spends!(node_txn[2], node_txn[1]);
4832
4833         mine_transaction(&nodes[1], &node_txn[0]);
4834         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4835         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4836
4837         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4838         assert_eq!(spend_txn.len(), 1);
4839         check_spends!(spend_txn[0], node_txn[0]);
4840 }
4841
4842 #[test]
4843 fn test_static_spendable_outputs_timeout_tx() {
4844         let chanmon_cfgs = create_chanmon_cfgs(2);
4845         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4846         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4847         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4848
4849         // Create some initial channels
4850         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4851
4852         // Rebalance the network a bit by relaying one payment through all the channels ...
4853         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4854
4855         let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4856
4857         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4858         assert_eq!(commitment_tx[0].input.len(), 1);
4859         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4860
4861         // Settle A's commitment tx on B' chain
4862         mine_transaction(&nodes[1], &commitment_tx[0]);
4863         check_added_monitors!(nodes[1], 1);
4864         let events = nodes[1].node.get_and_clear_pending_msg_events();
4865         match events[0] {
4866                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4867                 _ => panic!("Unexpected event"),
4868         }
4869         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4870
4871         // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4872         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4873         assert_eq!(node_txn.len(), 2); // ChannelManager : 1 local commitent tx, ChannelMonitor: timeout tx
4874         check_spends!(node_txn[0], chan_1.3.clone());
4875         check_spends!(node_txn[1],  commitment_tx[0].clone());
4876         assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4877
4878         mine_transaction(&nodes[1], &node_txn[1]);
4879         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4880         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4881         expect_payment_failed!(nodes[1], our_payment_hash, true);
4882
4883         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4884         assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4885         check_spends!(spend_txn[0], commitment_tx[0]);
4886         check_spends!(spend_txn[1], node_txn[1]);
4887         check_spends!(spend_txn[2], node_txn[1], commitment_tx[0]); // All outputs
4888 }
4889
4890 #[test]
4891 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4892         let chanmon_cfgs = create_chanmon_cfgs(2);
4893         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4894         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4895         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4896
4897         // Create some initial channels
4898         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4899
4900         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4901         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4902         assert_eq!(revoked_local_txn[0].input.len(), 1);
4903         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4904
4905         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4906
4907         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4908         check_closed_broadcast!(nodes[1], true);
4909         check_added_monitors!(nodes[1], 1);
4910         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4911
4912         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4913         assert_eq!(node_txn.len(), 2);
4914         assert_eq!(node_txn[0].input.len(), 2);
4915         check_spends!(node_txn[0], revoked_local_txn[0]);
4916
4917         mine_transaction(&nodes[1], &node_txn[0]);
4918         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4919
4920         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4921         assert_eq!(spend_txn.len(), 1);
4922         check_spends!(spend_txn[0], node_txn[0]);
4923 }
4924
4925 #[test]
4926 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4927         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4928         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4929         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4930         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4931         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4932
4933         // Create some initial channels
4934         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4935
4936         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4937         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4938         assert_eq!(revoked_local_txn[0].input.len(), 1);
4939         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4940
4941         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4942
4943         // A will generate HTLC-Timeout from revoked commitment tx
4944         mine_transaction(&nodes[0], &revoked_local_txn[0]);
4945         check_closed_broadcast!(nodes[0], true);
4946         check_added_monitors!(nodes[0], 1);
4947         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4948         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4949
4950         let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4951         assert_eq!(revoked_htlc_txn.len(), 2);
4952         check_spends!(revoked_htlc_txn[0], chan_1.3);
4953         assert_eq!(revoked_htlc_txn[1].input.len(), 1);
4954         assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4955         check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
4956         assert_ne!(revoked_htlc_txn[1].lock_time, 0); // HTLC-Timeout
4957
4958         // B will generate justice tx from A's revoked commitment/HTLC tx
4959         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4960         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[1].clone()] });
4961         check_closed_broadcast!(nodes[1], true);
4962         check_added_monitors!(nodes[1], 1);
4963         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4964
4965         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4966         assert_eq!(node_txn.len(), 3); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs, ChannelManager: local commitment tx
4967         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4968         // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
4969         // transactions next...
4970         assert_eq!(node_txn[0].input.len(), 3);
4971         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[1]);
4972
4973         assert_eq!(node_txn[1].input.len(), 2);
4974         check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[1]);
4975         if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[1].txid() {
4976                 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
4977         } else {
4978                 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[1].txid());
4979                 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[1].input[0].previous_output);
4980         }
4981
4982         assert_eq!(node_txn[2].input.len(), 1);
4983         check_spends!(node_txn[2], chan_1.3);
4984
4985         mine_transaction(&nodes[1], &node_txn[1]);
4986         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4987
4988         // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4989         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4990         assert_eq!(spend_txn.len(), 1);
4991         assert_eq!(spend_txn[0].input.len(), 1);
4992         check_spends!(spend_txn[0], node_txn[1]);
4993 }
4994
4995 #[test]
4996 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4997         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4998         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4999         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5000         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5001         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5002
5003         // Create some initial channels
5004         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5005
5006         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5007         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5008         assert_eq!(revoked_local_txn[0].input.len(), 1);
5009         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5010
5011         // The to-be-revoked commitment tx should have one HTLC and one to_remote output
5012         assert_eq!(revoked_local_txn[0].output.len(), 2);
5013
5014         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
5015
5016         // B will generate HTLC-Success from revoked commitment tx
5017         mine_transaction(&nodes[1], &revoked_local_txn[0]);
5018         check_closed_broadcast!(nodes[1], true);
5019         check_added_monitors!(nodes[1], 1);
5020         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5021         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5022
5023         assert_eq!(revoked_htlc_txn.len(), 2);
5024         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
5025         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5026         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
5027
5028         // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
5029         let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
5030         assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
5031
5032         // A will generate justice tx from B's revoked commitment/HTLC tx
5033         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5034         connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
5035         check_closed_broadcast!(nodes[0], true);
5036         check_added_monitors!(nodes[0], 1);
5037         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5038
5039         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5040         assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
5041
5042         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5043         // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
5044         // transactions next...
5045         assert_eq!(node_txn[0].input.len(), 2);
5046         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
5047         if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
5048                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5049         } else {
5050                 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
5051                 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5052         }
5053
5054         assert_eq!(node_txn[1].input.len(), 1);
5055         check_spends!(node_txn[1], revoked_htlc_txn[0]);
5056
5057         check_spends!(node_txn[2], chan_1.3);
5058
5059         mine_transaction(&nodes[0], &node_txn[1]);
5060         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5061
5062         // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
5063         // didn't try to generate any new transactions.
5064
5065         // Check A's ChannelMonitor was able to generate the right spendable output descriptor
5066         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5067         assert_eq!(spend_txn.len(), 3);
5068         assert_eq!(spend_txn[0].input.len(), 1);
5069         check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
5070         assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5071         check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
5072         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
5073 }
5074
5075 #[test]
5076 fn test_onchain_to_onchain_claim() {
5077         // Test that in case of channel closure, we detect the state of output and claim HTLC
5078         // on downstream peer's remote commitment tx.
5079         // First, have C claim an HTLC against its own latest commitment transaction.
5080         // Then, broadcast these to B, which should update the monitor downstream on the A<->B
5081         // channel.
5082         // Finally, check that B will claim the HTLC output if A's latest commitment transaction
5083         // gets broadcast.
5084
5085         let chanmon_cfgs = create_chanmon_cfgs(3);
5086         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5087         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5088         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5089
5090         // Create some initial channels
5091         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5092         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5093
5094         // Ensure all nodes are at the same height
5095         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5096         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5097         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5098         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5099
5100         // Rebalance the network a bit by relaying one payment through all the channels ...
5101         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5102         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5103
5104         let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
5105         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
5106         check_spends!(commitment_tx[0], chan_2.3);
5107         nodes[2].node.claim_funds(payment_preimage);
5108         check_added_monitors!(nodes[2], 1);
5109         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5110         assert!(updates.update_add_htlcs.is_empty());
5111         assert!(updates.update_fail_htlcs.is_empty());
5112         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5113         assert!(updates.update_fail_malformed_htlcs.is_empty());
5114
5115         mine_transaction(&nodes[2], &commitment_tx[0]);
5116         check_closed_broadcast!(nodes[2], true);
5117         check_added_monitors!(nodes[2], 1);
5118         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5119
5120         let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
5121         assert_eq!(c_txn.len(), 3);
5122         assert_eq!(c_txn[0], c_txn[2]);
5123         assert_eq!(commitment_tx[0], c_txn[1]);
5124         check_spends!(c_txn[1], chan_2.3);
5125         check_spends!(c_txn[2], c_txn[1]);
5126         assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
5127         assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5128         assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5129         assert_eq!(c_txn[0].lock_time, 0); // Success tx
5130
5131         // 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
5132         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
5133         connect_block(&nodes[1], &Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]});
5134         check_added_monitors!(nodes[1], 1);
5135         let events = nodes[1].node.get_and_clear_pending_events();
5136         assert_eq!(events.len(), 2);
5137         match events[0] {
5138                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5139                 _ => panic!("Unexpected event"),
5140         }
5141         match events[1] {
5142                 Event::PaymentForwarded { fee_earned_msat, source_channel_id, claim_from_onchain_tx } => {
5143                         assert_eq!(fee_earned_msat, Some(1000));
5144                         assert_eq!(source_channel_id, Some(chan_1.2));
5145                         assert_eq!(claim_from_onchain_tx, true);
5146                 },
5147                 _ => panic!("Unexpected event"),
5148         }
5149         {
5150                 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5151                 // ChannelMonitor: claim tx
5152                 assert_eq!(b_txn.len(), 1);
5153                 check_spends!(b_txn[0], chan_2.3); // B local commitment tx, issued by ChannelManager
5154                 b_txn.clear();
5155         }
5156         check_added_monitors!(nodes[1], 1);
5157         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5158         assert_eq!(msg_events.len(), 3);
5159         match msg_events[0] {
5160                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5161                 _ => panic!("Unexpected event"),
5162         }
5163         match msg_events[1] {
5164                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
5165                 _ => panic!("Unexpected event"),
5166         }
5167         match msg_events[2] {
5168                 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, .. } } => {
5169                         assert!(update_add_htlcs.is_empty());
5170                         assert!(update_fail_htlcs.is_empty());
5171                         assert_eq!(update_fulfill_htlcs.len(), 1);
5172                         assert!(update_fail_malformed_htlcs.is_empty());
5173                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5174                 },
5175                 _ => panic!("Unexpected event"),
5176         };
5177         // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
5178         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5179         mine_transaction(&nodes[1], &commitment_tx[0]);
5180         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5181         let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5182         // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
5183         assert_eq!(b_txn.len(), 3);
5184         check_spends!(b_txn[1], chan_1.3);
5185         check_spends!(b_txn[2], b_txn[1]);
5186         check_spends!(b_txn[0], commitment_tx[0]);
5187         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5188         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5189         assert_eq!(b_txn[0].lock_time, 0); // Success tx
5190
5191         check_closed_broadcast!(nodes[1], true);
5192         check_added_monitors!(nodes[1], 1);
5193 }
5194
5195 #[test]
5196 fn test_duplicate_payment_hash_one_failure_one_success() {
5197         // Topology : A --> B --> C --> D
5198         // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5199         // Note that because C will refuse to generate two payment secrets for the same payment hash,
5200         // we forward one of the payments onwards to D.
5201         let chanmon_cfgs = create_chanmon_cfgs(4);
5202         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
5203         // When this test was written, the default base fee floated based on the HTLC count.
5204         // It is now fixed, so we simply set the fee to the expected value here.
5205         let mut config = test_default_channel_config();
5206         config.channel_options.forwarding_fee_base_msat = 196;
5207         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
5208                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5209         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
5210
5211         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5212         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5213         create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5214
5215         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5216         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5217         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5218         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5219         connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
5220
5221         let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
5222
5223         let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200).unwrap();
5224         // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
5225         // script push size limit so that the below script length checks match
5226         // ACCEPTED_HTLC_SCRIPT_WEIGHT.
5227         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id())
5228                 .with_features(InvoiceFeatures::known());
5229         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 900000, TEST_FINAL_CLTV - 40);
5230         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 900000, duplicate_payment_hash, payment_secret);
5231
5232         let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5233         assert_eq!(commitment_txn[0].input.len(), 1);
5234         check_spends!(commitment_txn[0], chan_2.3);
5235
5236         mine_transaction(&nodes[1], &commitment_txn[0]);
5237         check_closed_broadcast!(nodes[1], true);
5238         check_added_monitors!(nodes[1], 1);
5239         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5240         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
5241
5242         let htlc_timeout_tx;
5243         { // Extract one of the two HTLC-Timeout transaction
5244                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5245                 // ChannelMonitor: timeout tx * 3, ChannelManager: local commitment tx
5246                 assert_eq!(node_txn.len(), 4);
5247                 check_spends!(node_txn[0], chan_2.3);
5248
5249                 check_spends!(node_txn[1], commitment_txn[0]);
5250                 assert_eq!(node_txn[1].input.len(), 1);
5251                 check_spends!(node_txn[2], commitment_txn[0]);
5252                 assert_eq!(node_txn[2].input.len(), 1);
5253                 assert_eq!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
5254                 check_spends!(node_txn[3], commitment_txn[0]);
5255                 assert_ne!(node_txn[1].input[0].previous_output, node_txn[3].input[0].previous_output);
5256
5257                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5258                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5259                 assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5260                 htlc_timeout_tx = node_txn[1].clone();
5261         }
5262
5263         nodes[2].node.claim_funds(our_payment_preimage);
5264         mine_transaction(&nodes[2], &commitment_txn[0]);
5265         check_added_monitors!(nodes[2], 2);
5266         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5267         let events = nodes[2].node.get_and_clear_pending_msg_events();
5268         match events[0] {
5269                 MessageSendEvent::UpdateHTLCs { .. } => {},
5270                 _ => panic!("Unexpected event"),
5271         }
5272         match events[1] {
5273                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5274                 _ => panic!("Unexepected event"),
5275         }
5276         let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5277         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)
5278         check_spends!(htlc_success_txn[0], commitment_txn[0]);
5279         check_spends!(htlc_success_txn[1], commitment_txn[0]);
5280         assert_eq!(htlc_success_txn[0].input.len(), 1);
5281         assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5282         assert_eq!(htlc_success_txn[1].input.len(), 1);
5283         assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5284         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
5285         assert_eq!(htlc_success_txn[2], commitment_txn[0]);
5286         assert_eq!(htlc_success_txn[3], htlc_success_txn[0]);
5287         assert_eq!(htlc_success_txn[4], htlc_success_txn[1]);
5288         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
5289
5290         mine_transaction(&nodes[1], &htlc_timeout_tx);
5291         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5292         expect_pending_htlcs_forwardable!(nodes[1]);
5293         let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5294         assert!(htlc_updates.update_add_htlcs.is_empty());
5295         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5296         let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
5297         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5298         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5299         check_added_monitors!(nodes[1], 1);
5300
5301         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5302         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5303         {
5304                 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5305         }
5306         expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
5307
5308         // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5309         // Note that the fee paid is effectively double as the HTLC value (including the nodes[1] fee
5310         // and nodes[2] fee) is rounded down and then claimed in full.
5311         mine_transaction(&nodes[1], &htlc_success_txn[0]);
5312         expect_payment_forwarded!(nodes[1], nodes[0], Some(196*2), true);
5313         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5314         assert!(updates.update_add_htlcs.is_empty());
5315         assert!(updates.update_fail_htlcs.is_empty());
5316         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5317         assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
5318         assert!(updates.update_fail_malformed_htlcs.is_empty());
5319         check_added_monitors!(nodes[1], 1);
5320
5321         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5322         commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5323
5324         let events = nodes[0].node.get_and_clear_pending_events();
5325         match events[0] {
5326                 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
5327                         assert_eq!(*payment_preimage, our_payment_preimage);
5328                         assert_eq!(*payment_hash, duplicate_payment_hash);
5329                 }
5330                 _ => panic!("Unexpected event"),
5331         }
5332 }
5333
5334 #[test]
5335 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5336         let chanmon_cfgs = create_chanmon_cfgs(2);
5337         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5338         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5339         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5340
5341         // Create some initial channels
5342         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5343
5344         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
5345         let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5346         assert_eq!(local_txn.len(), 1);
5347         assert_eq!(local_txn[0].input.len(), 1);
5348         check_spends!(local_txn[0], chan_1.3);
5349
5350         // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5351         nodes[1].node.claim_funds(payment_preimage);
5352         check_added_monitors!(nodes[1], 1);
5353         mine_transaction(&nodes[1], &local_txn[0]);
5354         check_added_monitors!(nodes[1], 1);
5355         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5356         let events = nodes[1].node.get_and_clear_pending_msg_events();
5357         match events[0] {
5358                 MessageSendEvent::UpdateHTLCs { .. } => {},
5359                 _ => panic!("Unexpected event"),
5360         }
5361         match events[1] {
5362                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5363                 _ => panic!("Unexepected event"),
5364         }
5365         let node_tx = {
5366                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5367                 assert_eq!(node_txn.len(), 3);
5368                 assert_eq!(node_txn[0], node_txn[2]);
5369                 assert_eq!(node_txn[1], local_txn[0]);
5370                 assert_eq!(node_txn[0].input.len(), 1);
5371                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5372                 check_spends!(node_txn[0], local_txn[0]);
5373                 node_txn[0].clone()
5374         };
5375
5376         mine_transaction(&nodes[1], &node_tx);
5377         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
5378
5379         // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5380         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5381         assert_eq!(spend_txn.len(), 1);
5382         assert_eq!(spend_txn[0].input.len(), 1);
5383         check_spends!(spend_txn[0], node_tx);
5384         assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5385 }
5386
5387 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5388         // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5389         // unrevoked commitment transaction.
5390         // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5391         // a remote RAA before they could be failed backwards (and combinations thereof).
5392         // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5393         // use the same payment hashes.
5394         // Thus, we use a six-node network:
5395         //
5396         // A \         / E
5397         //    - C - D -
5398         // B /         \ F
5399         // And test where C fails back to A/B when D announces its latest commitment transaction
5400         let chanmon_cfgs = create_chanmon_cfgs(6);
5401         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5402         // When this test was written, the default base fee floated based on the HTLC count.
5403         // It is now fixed, so we simply set the fee to the expected value here.
5404         let mut config = test_default_channel_config();
5405         config.channel_options.forwarding_fee_base_msat = 196;
5406         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
5407                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5408         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5409
5410         create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5411         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5412         let chan = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5413         create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
5414         create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
5415
5416         // Rebalance and check output sanity...
5417         send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
5418         send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
5419         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 2);
5420
5421         let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
5422         // 0th HTLC:
5423         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
5424         // 1st HTLC:
5425         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
5426         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5427         // 2nd HTLC:
5428         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
5429         // 3rd HTLC:
5430         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
5431         // 4th HTLC:
5432         let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5433         // 5th HTLC:
5434         let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5435         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5436         // 6th HTLC:
5437         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());
5438         // 7th HTLC:
5439         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());
5440
5441         // 8th HTLC:
5442         let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5443         // 9th HTLC:
5444         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5445         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
5446
5447         // 10th HTLC:
5448         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
5449         // 11th HTLC:
5450         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5451         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());
5452
5453         // Double-check that six of the new HTLC were added
5454         // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5455         // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5456         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2).len(), 1);
5457         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 8);
5458
5459         // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5460         // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5461         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_1));
5462         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_3));
5463         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_5));
5464         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_6));
5465         check_added_monitors!(nodes[4], 0);
5466         expect_pending_htlcs_forwardable!(nodes[4]);
5467         check_added_monitors!(nodes[4], 1);
5468
5469         let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5470         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5471         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5472         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5473         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5474         commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5475
5476         // Fail 3rd below-dust and 7th above-dust HTLCs
5477         assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_2));
5478         assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_4));
5479         check_added_monitors!(nodes[5], 0);
5480         expect_pending_htlcs_forwardable!(nodes[5]);
5481         check_added_monitors!(nodes[5], 1);
5482
5483         let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5484         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5485         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5486         commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5487
5488         let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5489
5490         expect_pending_htlcs_forwardable!(nodes[3]);
5491         check_added_monitors!(nodes[3], 1);
5492         let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5493         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5494         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5495         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5496         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5497         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5498         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5499         if deliver_last_raa {
5500                 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5501         } else {
5502                 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5503         }
5504
5505         // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5506         // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5507         // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5508         // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5509         //
5510         // We now broadcast the latest commitment transaction, which *should* result in failures for
5511         // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5512         // the non-broadcast above-dust HTLCs.
5513         //
5514         // Alternatively, we may broadcast the previous commitment transaction, which should only
5515         // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5516         let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5517
5518         if announce_latest {
5519                 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5520         } else {
5521                 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5522         }
5523         let events = nodes[2].node.get_and_clear_pending_events();
5524         let close_event = if deliver_last_raa {
5525                 assert_eq!(events.len(), 2);
5526                 events[1].clone()
5527         } else {
5528                 assert_eq!(events.len(), 1);
5529                 events[0].clone()
5530         };
5531         match close_event {
5532                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5533                 _ => panic!("Unexpected event"),
5534         }
5535
5536         connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5537         check_closed_broadcast!(nodes[2], true);
5538         if deliver_last_raa {
5539                 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5540         } else {
5541                 expect_pending_htlcs_forwardable!(nodes[2]);
5542         }
5543         check_added_monitors!(nodes[2], 3);
5544
5545         let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5546         assert_eq!(cs_msgs.len(), 2);
5547         let mut a_done = false;
5548         for msg in cs_msgs {
5549                 match msg {
5550                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5551                                 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5552                                 // should be failed-backwards here.
5553                                 let target = if *node_id == nodes[0].node.get_our_node_id() {
5554                                         // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5555                                         for htlc in &updates.update_fail_htlcs {
5556                                                 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 });
5557                                         }
5558                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5559                                         assert!(!a_done);
5560                                         a_done = true;
5561                                         &nodes[0]
5562                                 } else {
5563                                         // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5564                                         for htlc in &updates.update_fail_htlcs {
5565                                                 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5566                                         }
5567                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5568                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5569                                         &nodes[1]
5570                                 };
5571                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5572                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5573                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5574                                 if announce_latest {
5575                                         target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5576                                         if *node_id == nodes[0].node.get_our_node_id() {
5577                                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5578                                         }
5579                                 }
5580                                 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5581                         },
5582                         _ => panic!("Unexpected event"),
5583                 }
5584         }
5585
5586         let as_events = nodes[0].node.get_and_clear_pending_events();
5587         assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5588         let mut as_failds = HashSet::new();
5589         let mut as_updates = 0;
5590         for event in as_events.iter() {
5591                 if let &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5592                         assert!(as_failds.insert(*payment_hash));
5593                         if *payment_hash != payment_hash_2 {
5594                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5595                         } else {
5596                                 assert!(!rejected_by_dest);
5597                         }
5598                         if network_update.is_some() {
5599                                 as_updates += 1;
5600                         }
5601                 } else { panic!("Unexpected event"); }
5602         }
5603         assert!(as_failds.contains(&payment_hash_1));
5604         assert!(as_failds.contains(&payment_hash_2));
5605         if announce_latest {
5606                 assert!(as_failds.contains(&payment_hash_3));
5607                 assert!(as_failds.contains(&payment_hash_5));
5608         }
5609         assert!(as_failds.contains(&payment_hash_6));
5610
5611         let bs_events = nodes[1].node.get_and_clear_pending_events();
5612         assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5613         let mut bs_failds = HashSet::new();
5614         let mut bs_updates = 0;
5615         for event in bs_events.iter() {
5616                 if let &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5617                         assert!(bs_failds.insert(*payment_hash));
5618                         if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5619                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5620                         } else {
5621                                 assert!(!rejected_by_dest);
5622                         }
5623                         if network_update.is_some() {
5624                                 bs_updates += 1;
5625                         }
5626                 } else { panic!("Unexpected event"); }
5627         }
5628         assert!(bs_failds.contains(&payment_hash_1));
5629         assert!(bs_failds.contains(&payment_hash_2));
5630         if announce_latest {
5631                 assert!(bs_failds.contains(&payment_hash_4));
5632         }
5633         assert!(bs_failds.contains(&payment_hash_5));
5634
5635         // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5636         // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5637         // unknown-preimage-etc, B should have gotten 2. Thus, in the
5638         // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5639         assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5640         assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5641 }
5642
5643 #[test]
5644 fn test_fail_backwards_latest_remote_announce_a() {
5645         do_test_fail_backwards_unrevoked_remote_announce(false, true);
5646 }
5647
5648 #[test]
5649 fn test_fail_backwards_latest_remote_announce_b() {
5650         do_test_fail_backwards_unrevoked_remote_announce(true, true);
5651 }
5652
5653 #[test]
5654 fn test_fail_backwards_previous_remote_announce() {
5655         do_test_fail_backwards_unrevoked_remote_announce(false, false);
5656         // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5657         // tested for in test_commitment_revoked_fail_backward_exhaustive()
5658 }
5659
5660 #[test]
5661 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5662         let chanmon_cfgs = create_chanmon_cfgs(2);
5663         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5664         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5665         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5666
5667         // Create some initial channels
5668         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5669
5670         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5671         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5672         assert_eq!(local_txn[0].input.len(), 1);
5673         check_spends!(local_txn[0], chan_1.3);
5674
5675         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5676         mine_transaction(&nodes[0], &local_txn[0]);
5677         check_closed_broadcast!(nodes[0], true);
5678         check_added_monitors!(nodes[0], 1);
5679         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5680         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5681
5682         let htlc_timeout = {
5683                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5684                 assert_eq!(node_txn.len(), 2);
5685                 check_spends!(node_txn[0], chan_1.3);
5686                 assert_eq!(node_txn[1].input.len(), 1);
5687                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5688                 check_spends!(node_txn[1], local_txn[0]);
5689                 node_txn[1].clone()
5690         };
5691
5692         mine_transaction(&nodes[0], &htlc_timeout);
5693         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5694         expect_payment_failed!(nodes[0], our_payment_hash, true);
5695
5696         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5697         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5698         assert_eq!(spend_txn.len(), 3);
5699         check_spends!(spend_txn[0], local_txn[0]);
5700         assert_eq!(spend_txn[1].input.len(), 1);
5701         check_spends!(spend_txn[1], htlc_timeout);
5702         assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5703         assert_eq!(spend_txn[2].input.len(), 2);
5704         check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5705         assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5706                 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5707 }
5708
5709 #[test]
5710 fn test_key_derivation_params() {
5711         // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5712         // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5713         // let us re-derive the channel key set to then derive a delayed_payment_key.
5714
5715         let chanmon_cfgs = create_chanmon_cfgs(3);
5716
5717         // We manually create the node configuration to backup the seed.
5718         let seed = [42; 32];
5719         let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5720         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);
5721         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() };
5722         let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5723         node_cfgs.remove(0);
5724         node_cfgs.insert(0, node);
5725
5726         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5727         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5728
5729         // Create some initial channels
5730         // Create a dummy channel to advance index by one and thus test re-derivation correctness
5731         // for node 0
5732         let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5733         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5734         assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5735
5736         // Ensure all nodes are at the same height
5737         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5738         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5739         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5740         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5741
5742         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5743         let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5744         let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5745         assert_eq!(local_txn_1[0].input.len(), 1);
5746         check_spends!(local_txn_1[0], chan_1.3);
5747
5748         // We check funding pubkey are unique
5749         let (from_0_funding_key_0, from_0_funding_key_1) = (PublicKey::from_slice(&local_txn_0[0].input[0].witness[3][2..35]), PublicKey::from_slice(&local_txn_0[0].input[0].witness[3][36..69]));
5750         let (from_1_funding_key_0, from_1_funding_key_1) = (PublicKey::from_slice(&local_txn_1[0].input[0].witness[3][2..35]), PublicKey::from_slice(&local_txn_1[0].input[0].witness[3][36..69]));
5751         if from_0_funding_key_0 == from_1_funding_key_0
5752             || from_0_funding_key_0 == from_1_funding_key_1
5753             || from_0_funding_key_1 == from_1_funding_key_0
5754             || from_0_funding_key_1 == from_1_funding_key_1 {
5755                 panic!("Funding pubkeys aren't unique");
5756         }
5757
5758         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5759         mine_transaction(&nodes[0], &local_txn_1[0]);
5760         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5761         check_closed_broadcast!(nodes[0], true);
5762         check_added_monitors!(nodes[0], 1);
5763         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5764
5765         let htlc_timeout = {
5766                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5767                 assert_eq!(node_txn[1].input.len(), 1);
5768                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5769                 check_spends!(node_txn[1], local_txn_1[0]);
5770                 node_txn[1].clone()
5771         };
5772
5773         mine_transaction(&nodes[0], &htlc_timeout);
5774         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5775         expect_payment_failed!(nodes[0], our_payment_hash, true);
5776
5777         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5778         let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5779         let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5780         assert_eq!(spend_txn.len(), 3);
5781         check_spends!(spend_txn[0], local_txn_1[0]);
5782         assert_eq!(spend_txn[1].input.len(), 1);
5783         check_spends!(spend_txn[1], htlc_timeout);
5784         assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5785         assert_eq!(spend_txn[2].input.len(), 2);
5786         check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5787         assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5788                 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5789 }
5790
5791 #[test]
5792 fn test_static_output_closing_tx() {
5793         let chanmon_cfgs = create_chanmon_cfgs(2);
5794         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5795         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5796         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5797
5798         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5799
5800         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5801         let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5802
5803         mine_transaction(&nodes[0], &closing_tx);
5804         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5805         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5806
5807         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5808         assert_eq!(spend_txn.len(), 1);
5809         check_spends!(spend_txn[0], closing_tx);
5810
5811         mine_transaction(&nodes[1], &closing_tx);
5812         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5813         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5814
5815         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5816         assert_eq!(spend_txn.len(), 1);
5817         check_spends!(spend_txn[0], closing_tx);
5818 }
5819
5820 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5821         let chanmon_cfgs = create_chanmon_cfgs(2);
5822         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5823         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5824         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5825         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5826
5827         let (payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3000000 });
5828
5829         // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5830         // present in B's local commitment transaction, but none of A's commitment transactions.
5831         assert!(nodes[1].node.claim_funds(payment_preimage));
5832         check_added_monitors!(nodes[1], 1);
5833
5834         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5835         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5836         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
5837
5838         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5839         check_added_monitors!(nodes[0], 1);
5840         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5841         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5842         check_added_monitors!(nodes[1], 1);
5843
5844         let starting_block = nodes[1].best_block_info();
5845         let mut block = Block {
5846                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5847                 txdata: vec![],
5848         };
5849         for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5850                 connect_block(&nodes[1], &block);
5851                 block.header.prev_blockhash = block.block_hash();
5852         }
5853         test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5854         check_closed_broadcast!(nodes[1], true);
5855         check_added_monitors!(nodes[1], 1);
5856         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5857 }
5858
5859 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5860         let chanmon_cfgs = create_chanmon_cfgs(2);
5861         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5862         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5863         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5864         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5865
5866         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5867         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
5868         check_added_monitors!(nodes[0], 1);
5869
5870         let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5871
5872         // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5873         // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5874         // to "time out" the HTLC.
5875
5876         let starting_block = nodes[1].best_block_info();
5877         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5878
5879         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5880                 connect_block(&nodes[0], &Block { header, txdata: Vec::new()});
5881                 header.prev_blockhash = header.block_hash();
5882         }
5883         test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5884         check_closed_broadcast!(nodes[0], true);
5885         check_added_monitors!(nodes[0], 1);
5886         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5887 }
5888
5889 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5890         let chanmon_cfgs = create_chanmon_cfgs(3);
5891         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5892         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5893         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5894         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5895
5896         // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5897         // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5898         // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5899         // actually revoked.
5900         let htlc_value = if use_dust { 50000 } else { 3000000 };
5901         let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5902         assert!(nodes[1].node.fail_htlc_backwards(&our_payment_hash));
5903         expect_pending_htlcs_forwardable!(nodes[1]);
5904         check_added_monitors!(nodes[1], 1);
5905
5906         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5907         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5908         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5909         check_added_monitors!(nodes[0], 1);
5910         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5911         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5912         check_added_monitors!(nodes[1], 1);
5913         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5914         check_added_monitors!(nodes[1], 1);
5915         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5916
5917         if check_revoke_no_close {
5918                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5919                 check_added_monitors!(nodes[0], 1);
5920         }
5921
5922         let starting_block = nodes[1].best_block_info();
5923         let mut block = Block {
5924                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5925                 txdata: vec![],
5926         };
5927         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5928                 connect_block(&nodes[0], &block);
5929                 block.header.prev_blockhash = block.block_hash();
5930         }
5931         if !check_revoke_no_close {
5932                 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5933                 check_closed_broadcast!(nodes[0], true);
5934                 check_added_monitors!(nodes[0], 1);
5935                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5936         } else {
5937                 let events = nodes[0].node.get_and_clear_pending_events();
5938                 assert_eq!(events.len(), 2);
5939                 if let Event::PaymentPathFailed { ref payment_hash, .. } = events[0] {
5940                         assert_eq!(*payment_hash, our_payment_hash);
5941                 } else { panic!("Unexpected event"); }
5942                 if let Event::PaymentFailed { ref payment_hash, .. } = events[1] {
5943                         assert_eq!(*payment_hash, our_payment_hash);
5944                 } else { panic!("Unexpected event"); }
5945         }
5946 }
5947
5948 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5949 // There are only a few cases to test here:
5950 //  * its not really normative behavior, but we test that below-dust HTLCs "included" in
5951 //    broadcastable commitment transactions result in channel closure,
5952 //  * its included in an unrevoked-but-previous remote commitment transaction,
5953 //  * its included in the latest remote or local commitment transactions.
5954 // We test each of the three possible commitment transactions individually and use both dust and
5955 // non-dust HTLCs.
5956 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5957 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5958 // tested for at least one of the cases in other tests.
5959 #[test]
5960 fn htlc_claim_single_commitment_only_a() {
5961         do_htlc_claim_local_commitment_only(true);
5962         do_htlc_claim_local_commitment_only(false);
5963
5964         do_htlc_claim_current_remote_commitment_only(true);
5965         do_htlc_claim_current_remote_commitment_only(false);
5966 }
5967
5968 #[test]
5969 fn htlc_claim_single_commitment_only_b() {
5970         do_htlc_claim_previous_remote_commitment_only(true, false);
5971         do_htlc_claim_previous_remote_commitment_only(false, false);
5972         do_htlc_claim_previous_remote_commitment_only(true, true);
5973         do_htlc_claim_previous_remote_commitment_only(false, true);
5974 }
5975
5976 #[test]
5977 #[should_panic]
5978 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5979         let chanmon_cfgs = create_chanmon_cfgs(2);
5980         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5981         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5982         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5983         // Force duplicate randomness for every get-random call
5984         for node in nodes.iter() {
5985                 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
5986         }
5987
5988         // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5989         let channel_value_satoshis=10000;
5990         let push_msat=10001;
5991         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5992         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5993         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
5994         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
5995
5996         // Create a second channel with the same random values. This used to panic due to a colliding
5997         // channel_id, but now panics due to a colliding outbound SCID alias.
5998         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5999 }
6000
6001 #[test]
6002 fn bolt2_open_channel_sending_node_checks_part2() {
6003         let chanmon_cfgs = create_chanmon_cfgs(2);
6004         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6005         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6006         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6007
6008         // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
6009         let channel_value_satoshis=2^24;
6010         let push_msat=10001;
6011         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6012
6013         // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
6014         let channel_value_satoshis=10000;
6015         // Test when push_msat is equal to 1000 * funding_satoshis.
6016         let push_msat=1000*channel_value_satoshis+1;
6017         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6018
6019         // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
6020         let channel_value_satoshis=10000;
6021         let push_msat=10001;
6022         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
6023         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6024         assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
6025
6026         // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
6027         // 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
6028         assert!(node0_to_1_send_open_channel.channel_flags<=1);
6029
6030         // 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.
6031         assert!(BREAKDOWN_TIMEOUT>0);
6032         assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
6033
6034         // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
6035         let chain_hash=genesis_block(Network::Testnet).header.block_hash();
6036         assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
6037
6038         // 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.
6039         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
6040         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
6041         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
6042         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
6043         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
6044 }
6045
6046 #[test]
6047 fn bolt2_open_channel_sane_dust_limit() {
6048         let chanmon_cfgs = create_chanmon_cfgs(2);
6049         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6050         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6051         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6052
6053         let channel_value_satoshis=1000000;
6054         let push_msat=10001;
6055         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
6056         let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6057         node0_to_1_send_open_channel.dust_limit_satoshis = 547;
6058         node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
6059
6060         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
6061         let events = nodes[1].node.get_and_clear_pending_msg_events();
6062         let err_msg = match events[0] {
6063                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
6064                         msg.clone()
6065                 },
6066                 _ => panic!("Unexpected event"),
6067         };
6068         assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
6069 }
6070
6071 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
6072 // originated from our node, its failure is surfaced to the user. We trigger this failure to
6073 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
6074 // is no longer affordable once it's freed.
6075 #[test]
6076 fn test_fail_holding_cell_htlc_upon_free() {
6077         let chanmon_cfgs = create_chanmon_cfgs(2);
6078         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6079         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6080         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6081         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6082
6083         // First nodes[0] generates an update_fee, setting the channel's
6084         // pending_update_fee.
6085         {
6086                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6087                 *feerate_lock += 20;
6088         }
6089         nodes[0].node.timer_tick_occurred();
6090         check_added_monitors!(nodes[0], 1);
6091
6092         let events = nodes[0].node.get_and_clear_pending_msg_events();
6093         assert_eq!(events.len(), 1);
6094         let (update_msg, commitment_signed) = match events[0] {
6095                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6096                         (update_fee.as_ref(), commitment_signed)
6097                 },
6098                 _ => panic!("Unexpected event"),
6099         };
6100
6101         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6102
6103         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6104         let channel_reserve = chan_stat.channel_reserve_msat;
6105         let feerate = get_feerate!(nodes[0], chan.2);
6106         let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6107
6108         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6109         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6110         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6111
6112         // Send a payment which passes reserve checks but gets stuck in the holding cell.
6113         let our_payment_id = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6114         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6115         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6116
6117         // Flush the pending fee update.
6118         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6119         let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6120         check_added_monitors!(nodes[1], 1);
6121         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
6122         check_added_monitors!(nodes[0], 1);
6123
6124         // Upon receipt of the RAA, there will be an attempt to resend the holding cell
6125         // HTLC, but now that the fee has been raised the payment will now fail, causing
6126         // us to surface its failure to the user.
6127         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6128         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6129         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);
6130         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 {}",
6131                 hex::encode(our_payment_hash.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6132         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6133
6134         // Check that the payment failed to be sent out.
6135         let events = nodes[0].node.get_and_clear_pending_events();
6136         assert_eq!(events.len(), 1);
6137         match &events[0] {
6138                 &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, .. } => {
6139                         assert_eq!(our_payment_id, *payment_id.as_ref().unwrap());
6140                         assert_eq!(our_payment_hash.clone(), *payment_hash);
6141                         assert_eq!(*rejected_by_dest, false);
6142                         assert_eq!(*all_paths_failed, true);
6143                         assert_eq!(*network_update, None);
6144                         assert_eq!(*short_channel_id, None);
6145                         assert_eq!(*error_code, None);
6146                         assert_eq!(*error_data, None);
6147                 },
6148                 _ => panic!("Unexpected event"),
6149         }
6150 }
6151
6152 // Test that if multiple HTLCs are released from the holding cell and one is
6153 // valid but the other is no longer valid upon release, the valid HTLC can be
6154 // successfully completed while the other one fails as expected.
6155 #[test]
6156 fn test_free_and_fail_holding_cell_htlcs() {
6157         let chanmon_cfgs = create_chanmon_cfgs(2);
6158         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6159         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6160         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6161         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6162
6163         // First nodes[0] generates an update_fee, setting the channel's
6164         // pending_update_fee.
6165         {
6166                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6167                 *feerate_lock += 200;
6168         }
6169         nodes[0].node.timer_tick_occurred();
6170         check_added_monitors!(nodes[0], 1);
6171
6172         let events = nodes[0].node.get_and_clear_pending_msg_events();
6173         assert_eq!(events.len(), 1);
6174         let (update_msg, commitment_signed) = match events[0] {
6175                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6176                         (update_fee.as_ref(), commitment_signed)
6177                 },
6178                 _ => panic!("Unexpected event"),
6179         };
6180
6181         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6182
6183         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6184         let channel_reserve = chan_stat.channel_reserve_msat;
6185         let feerate = get_feerate!(nodes[0], chan.2);
6186         let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6187
6188         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6189         let amt_1 = 20000;
6190         let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors) - amt_1;
6191         let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
6192         let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
6193
6194         // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6195         nodes[0].node.send_payment(&route_1, payment_hash_1, &Some(payment_secret_1)).unwrap();
6196         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6197         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6198         let payment_id_2 = nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
6199         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6200         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6201
6202         // Flush the pending fee update.
6203         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6204         let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6205         check_added_monitors!(nodes[1], 1);
6206         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6207         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6208         check_added_monitors!(nodes[0], 2);
6209
6210         // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6211         // but now that the fee has been raised the second payment will now fail, causing us
6212         // to surface its failure to the user. The first payment should succeed.
6213         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6214         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6215         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);
6216         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 {}",
6217                 hex::encode(payment_hash_2.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6218         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6219
6220         // Check that the second payment failed to be sent out.
6221         let events = nodes[0].node.get_and_clear_pending_events();
6222         assert_eq!(events.len(), 1);
6223         match &events[0] {
6224                 &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, .. } => {
6225                         assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
6226                         assert_eq!(payment_hash_2.clone(), *payment_hash);
6227                         assert_eq!(*rejected_by_dest, false);
6228                         assert_eq!(*all_paths_failed, true);
6229                         assert_eq!(*network_update, None);
6230                         assert_eq!(*short_channel_id, None);
6231                         assert_eq!(*error_code, None);
6232                         assert_eq!(*error_data, None);
6233                 },
6234                 _ => panic!("Unexpected event"),
6235         }
6236
6237         // Complete the first payment and the RAA from the fee update.
6238         let (payment_event, send_raa_event) = {
6239                 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6240                 assert_eq!(msgs.len(), 2);
6241                 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6242         };
6243         let raa = match send_raa_event {
6244                 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6245                 _ => panic!("Unexpected event"),
6246         };
6247         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6248         check_added_monitors!(nodes[1], 1);
6249         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6250         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6251         let events = nodes[1].node.get_and_clear_pending_events();
6252         assert_eq!(events.len(), 1);
6253         match events[0] {
6254                 Event::PendingHTLCsForwardable { .. } => {},
6255                 _ => panic!("Unexpected event"),
6256         }
6257         nodes[1].node.process_pending_htlc_forwards();
6258         let events = nodes[1].node.get_and_clear_pending_events();
6259         assert_eq!(events.len(), 1);
6260         match events[0] {
6261                 Event::PaymentReceived { .. } => {},
6262                 _ => panic!("Unexpected event"),
6263         }
6264         nodes[1].node.claim_funds(payment_preimage_1);
6265         check_added_monitors!(nodes[1], 1);
6266         let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6267         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6268         commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6269         expect_payment_sent!(nodes[0], payment_preimage_1);
6270 }
6271
6272 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6273 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6274 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6275 // once it's freed.
6276 #[test]
6277 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6278         let chanmon_cfgs = create_chanmon_cfgs(3);
6279         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6280         // When this test was written, the default base fee floated based on the HTLC count.
6281         // It is now fixed, so we simply set the fee to the expected value here.
6282         let mut config = test_default_channel_config();
6283         config.channel_options.forwarding_fee_base_msat = 196;
6284         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
6285         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6286         let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6287         let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6288
6289         // First nodes[1] generates an update_fee, setting the channel's
6290         // pending_update_fee.
6291         {
6292                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
6293                 *feerate_lock += 20;
6294         }
6295         nodes[1].node.timer_tick_occurred();
6296         check_added_monitors!(nodes[1], 1);
6297
6298         let events = nodes[1].node.get_and_clear_pending_msg_events();
6299         assert_eq!(events.len(), 1);
6300         let (update_msg, commitment_signed) = match events[0] {
6301                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6302                         (update_fee.as_ref(), commitment_signed)
6303                 },
6304                 _ => panic!("Unexpected event"),
6305         };
6306
6307         nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6308
6309         let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
6310         let channel_reserve = chan_stat.channel_reserve_msat;
6311         let feerate = get_feerate!(nodes[0], chan_0_1.2);
6312         let opt_anchors = get_opt_anchors!(nodes[0], chan_0_1.2);
6313
6314         // Send a payment which passes reserve checks but gets stuck in the holding cell.
6315         let feemsat = 239;
6316         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
6317         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors) - total_routing_fee_msat;
6318         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
6319         let payment_event = {
6320                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6321                 check_added_monitors!(nodes[0], 1);
6322
6323                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6324                 assert_eq!(events.len(), 1);
6325
6326                 SendEvent::from_event(events.remove(0))
6327         };
6328         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6329         check_added_monitors!(nodes[1], 0);
6330         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6331         expect_pending_htlcs_forwardable!(nodes[1]);
6332
6333         chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
6334         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6335
6336         // Flush the pending fee update.
6337         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6338         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6339         check_added_monitors!(nodes[2], 1);
6340         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6341         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6342         check_added_monitors!(nodes[1], 2);
6343
6344         // A final RAA message is generated to finalize the fee update.
6345         let events = nodes[1].node.get_and_clear_pending_msg_events();
6346         assert_eq!(events.len(), 1);
6347
6348         let raa_msg = match &events[0] {
6349                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6350                         msg.clone()
6351                 },
6352                 _ => panic!("Unexpected event"),
6353         };
6354
6355         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6356         check_added_monitors!(nodes[2], 1);
6357         assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6358
6359         // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6360         let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6361         assert_eq!(process_htlc_forwards_event.len(), 1);
6362         match &process_htlc_forwards_event[0] {
6363                 &Event::PendingHTLCsForwardable { .. } => {},
6364                 _ => panic!("Unexpected event"),
6365         }
6366
6367         // In response, we call ChannelManager's process_pending_htlc_forwards
6368         nodes[1].node.process_pending_htlc_forwards();
6369         check_added_monitors!(nodes[1], 1);
6370
6371         // This causes the HTLC to be failed backwards.
6372         let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6373         assert_eq!(fail_event.len(), 1);
6374         let (fail_msg, commitment_signed) = match &fail_event[0] {
6375                 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6376                         assert_eq!(updates.update_add_htlcs.len(), 0);
6377                         assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6378                         assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6379                         assert_eq!(updates.update_fail_htlcs.len(), 1);
6380                         (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6381                 },
6382                 _ => panic!("Unexpected event"),
6383         };
6384
6385         // Pass the failure messages back to nodes[0].
6386         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6387         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6388
6389         // Complete the HTLC failure+removal process.
6390         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6391         check_added_monitors!(nodes[0], 1);
6392         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6393         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6394         check_added_monitors!(nodes[1], 2);
6395         let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6396         assert_eq!(final_raa_event.len(), 1);
6397         let raa = match &final_raa_event[0] {
6398                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6399                 _ => panic!("Unexpected event"),
6400         };
6401         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6402         expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6403         check_added_monitors!(nodes[0], 1);
6404 }
6405
6406 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6407 // 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.
6408 //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.
6409
6410 #[test]
6411 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6412         //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6413         let chanmon_cfgs = create_chanmon_cfgs(2);
6414         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6415         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6416         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6417         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6418
6419         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6420         route.paths[0][0].fee_msat = 100;
6421
6422         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6423                 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6424         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6425         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6426 }
6427
6428 #[test]
6429 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6430         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6431         let chanmon_cfgs = create_chanmon_cfgs(2);
6432         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6433         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6434         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6435         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6436
6437         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6438         route.paths[0][0].fee_msat = 0;
6439         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6440                 assert_eq!(err, "Cannot send 0-msat HTLC"));
6441
6442         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6443         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6444 }
6445
6446 #[test]
6447 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6448         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6449         let chanmon_cfgs = create_chanmon_cfgs(2);
6450         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6451         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6452         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6453         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6454
6455         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6456         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6457         check_added_monitors!(nodes[0], 1);
6458         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6459         updates.update_add_htlcs[0].amount_msat = 0;
6460
6461         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6462         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6463         check_closed_broadcast!(nodes[1], true).unwrap();
6464         check_added_monitors!(nodes[1], 1);
6465         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
6466 }
6467
6468 #[test]
6469 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6470         //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6471         //It is enforced when constructing a route.
6472         let chanmon_cfgs = create_chanmon_cfgs(2);
6473         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6474         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6475         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6476         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6477
6478         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
6479                 .with_features(InvoiceFeatures::known());
6480         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000, 0);
6481         route.paths[0].last_mut().unwrap().cltv_expiry_delta = 500000001;
6482         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::RouteError { ref err },
6483                 assert_eq!(err, &"Channel CLTV overflowed?"));
6484 }
6485
6486 #[test]
6487 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6488         //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.
6489         //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6490         //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6491         let chanmon_cfgs = create_chanmon_cfgs(2);
6492         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6493         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6494         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6495         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6496         let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6497
6498         for i in 0..max_accepted_htlcs {
6499                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6500                 let payment_event = {
6501                         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6502                         check_added_monitors!(nodes[0], 1);
6503
6504                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6505                         assert_eq!(events.len(), 1);
6506                         if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6507                                 assert_eq!(htlcs[0].htlc_id, i);
6508                         } else {
6509                                 assert!(false);
6510                         }
6511                         SendEvent::from_event(events.remove(0))
6512                 };
6513                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6514                 check_added_monitors!(nodes[1], 0);
6515                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6516
6517                 expect_pending_htlcs_forwardable!(nodes[1]);
6518                 expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6519         }
6520         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6521         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6522                 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6523
6524         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6525         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6526 }
6527
6528 #[test]
6529 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6530         //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.
6531         let chanmon_cfgs = create_chanmon_cfgs(2);
6532         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6533         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6534         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6535         let channel_value = 100000;
6536         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::known(), InitFeatures::known());
6537         let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6538
6539         send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6540
6541         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6542         // Manually create a route over our max in flight (which our router normally automatically
6543         // limits us to.
6544         route.paths[0][0].fee_msat =  max_in_flight + 1;
6545         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6546                 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)));
6547
6548         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6549         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);
6550
6551         send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6552 }
6553
6554 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6555 #[test]
6556 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6557         //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6558         let chanmon_cfgs = create_chanmon_cfgs(2);
6559         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6560         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6561         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6562         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6563         let htlc_minimum_msat: u64;
6564         {
6565                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6566                 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6567                 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6568         }
6569
6570         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6571         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6572         check_added_monitors!(nodes[0], 1);
6573         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6574         updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6575         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6576         assert!(nodes[1].node.list_channels().is_empty());
6577         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6578         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()));
6579         check_added_monitors!(nodes[1], 1);
6580         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6581 }
6582
6583 #[test]
6584 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6585         //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
6586         let chanmon_cfgs = create_chanmon_cfgs(2);
6587         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6588         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6589         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6590         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6591
6592         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6593         let channel_reserve = chan_stat.channel_reserve_msat;
6594         let feerate = get_feerate!(nodes[0], chan.2);
6595         let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6596         // The 2* and +1 are for the fee spike reserve.
6597         let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6598
6599         let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6600         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6601         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6602         check_added_monitors!(nodes[0], 1);
6603         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6604
6605         // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6606         // at this time channel-initiatee receivers are not required to enforce that senders
6607         // respect the fee_spike_reserve.
6608         updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6609         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6610
6611         assert!(nodes[1].node.list_channels().is_empty());
6612         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6613         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6614         check_added_monitors!(nodes[1], 1);
6615         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6616 }
6617
6618 #[test]
6619 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6620         //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6621         //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6622         let chanmon_cfgs = create_chanmon_cfgs(2);
6623         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6624         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6625         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6626         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6627
6628         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3999999);
6629         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6630         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6631         let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6632         let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &Some(our_payment_secret), cur_height, &None).unwrap();
6633         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6634
6635         let mut msg = msgs::UpdateAddHTLC {
6636                 channel_id: chan.2,
6637                 htlc_id: 0,
6638                 amount_msat: 1000,
6639                 payment_hash: our_payment_hash,
6640                 cltv_expiry: htlc_cltv,
6641                 onion_routing_packet: onion_packet.clone(),
6642         };
6643
6644         for i in 0..super::channel::OUR_MAX_HTLCS {
6645                 msg.htlc_id = i as u64;
6646                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6647         }
6648         msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6649         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6650
6651         assert!(nodes[1].node.list_channels().is_empty());
6652         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6653         assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6654         check_added_monitors!(nodes[1], 1);
6655         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6656 }
6657
6658 #[test]
6659 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6660         //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6661         let chanmon_cfgs = create_chanmon_cfgs(2);
6662         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6663         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6664         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6665         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6666
6667         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6668         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6669         check_added_monitors!(nodes[0], 1);
6670         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6671         updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6672         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6673
6674         assert!(nodes[1].node.list_channels().is_empty());
6675         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6676         assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6677         check_added_monitors!(nodes[1], 1);
6678         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6679 }
6680
6681 #[test]
6682 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6683         //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6684         let chanmon_cfgs = create_chanmon_cfgs(2);
6685         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6686         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6687         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6688
6689         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6690         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6691         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6692         check_added_monitors!(nodes[0], 1);
6693         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6694         updates.update_add_htlcs[0].cltv_expiry = 500000000;
6695         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6696
6697         assert!(nodes[1].node.list_channels().is_empty());
6698         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6699         assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6700         check_added_monitors!(nodes[1], 1);
6701         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6702 }
6703
6704 #[test]
6705 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6706         //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6707         // We test this by first testing that that repeated HTLCs pass commitment signature checks
6708         // after disconnect and that non-sequential htlc_ids result in a channel failure.
6709         let chanmon_cfgs = create_chanmon_cfgs(2);
6710         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6711         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6712         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6713
6714         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6715         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6716         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6717         check_added_monitors!(nodes[0], 1);
6718         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6719         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6720
6721         //Disconnect and Reconnect
6722         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6723         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6724         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
6725         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6726         assert_eq!(reestablish_1.len(), 1);
6727         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
6728         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6729         assert_eq!(reestablish_2.len(), 1);
6730         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6731         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6732         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6733         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6734
6735         //Resend HTLC
6736         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6737         assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6738         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6739         check_added_monitors!(nodes[1], 1);
6740         let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6741
6742         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6743
6744         assert!(nodes[1].node.list_channels().is_empty());
6745         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6746         assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6747         check_added_monitors!(nodes[1], 1);
6748         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6749 }
6750
6751 #[test]
6752 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6753         //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.
6754
6755         let chanmon_cfgs = create_chanmon_cfgs(2);
6756         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6757         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6758         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6759         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6760         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6761         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6762
6763         check_added_monitors!(nodes[0], 1);
6764         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6765         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6766
6767         let update_msg = msgs::UpdateFulfillHTLC{
6768                 channel_id: chan.2,
6769                 htlc_id: 0,
6770                 payment_preimage: our_payment_preimage,
6771         };
6772
6773         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6774
6775         assert!(nodes[0].node.list_channels().is_empty());
6776         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6777         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()));
6778         check_added_monitors!(nodes[0], 1);
6779         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6780 }
6781
6782 #[test]
6783 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6784         //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.
6785
6786         let chanmon_cfgs = create_chanmon_cfgs(2);
6787         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6788         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6789         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6790         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6791
6792         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6793         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6794         check_added_monitors!(nodes[0], 1);
6795         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6796         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6797
6798         let update_msg = msgs::UpdateFailHTLC{
6799                 channel_id: chan.2,
6800                 htlc_id: 0,
6801                 reason: msgs::OnionErrorPacket { data: Vec::new()},
6802         };
6803
6804         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6805
6806         assert!(nodes[0].node.list_channels().is_empty());
6807         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6808         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()));
6809         check_added_monitors!(nodes[0], 1);
6810         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6811 }
6812
6813 #[test]
6814 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6815         //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.
6816
6817         let chanmon_cfgs = create_chanmon_cfgs(2);
6818         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6819         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6820         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6821         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6822
6823         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6824         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6825         check_added_monitors!(nodes[0], 1);
6826         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6827         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6828         let update_msg = msgs::UpdateFailMalformedHTLC{
6829                 channel_id: chan.2,
6830                 htlc_id: 0,
6831                 sha256_of_onion: [1; 32],
6832                 failure_code: 0x8000,
6833         };
6834
6835         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6836
6837         assert!(nodes[0].node.list_channels().is_empty());
6838         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6839         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()));
6840         check_added_monitors!(nodes[0], 1);
6841         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6842 }
6843
6844 #[test]
6845 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6846         //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6847
6848         let chanmon_cfgs = create_chanmon_cfgs(2);
6849         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6850         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6851         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6852         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6853
6854         let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6855
6856         nodes[1].node.claim_funds(our_payment_preimage);
6857         check_added_monitors!(nodes[1], 1);
6858
6859         let events = nodes[1].node.get_and_clear_pending_msg_events();
6860         assert_eq!(events.len(), 1);
6861         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6862                 match events[0] {
6863                         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, .. } } => {
6864                                 assert!(update_add_htlcs.is_empty());
6865                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6866                                 assert!(update_fail_htlcs.is_empty());
6867                                 assert!(update_fail_malformed_htlcs.is_empty());
6868                                 assert!(update_fee.is_none());
6869                                 update_fulfill_htlcs[0].clone()
6870                         },
6871                         _ => panic!("Unexpected event"),
6872                 }
6873         };
6874
6875         update_fulfill_msg.htlc_id = 1;
6876
6877         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6878
6879         assert!(nodes[0].node.list_channels().is_empty());
6880         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6881         assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6882         check_added_monitors!(nodes[0], 1);
6883         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6884 }
6885
6886 #[test]
6887 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6888         //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.
6889
6890         let chanmon_cfgs = create_chanmon_cfgs(2);
6891         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6892         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6893         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6894         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6895
6896         let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6897
6898         nodes[1].node.claim_funds(our_payment_preimage);
6899         check_added_monitors!(nodes[1], 1);
6900
6901         let events = nodes[1].node.get_and_clear_pending_msg_events();
6902         assert_eq!(events.len(), 1);
6903         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6904                 match events[0] {
6905                         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, .. } } => {
6906                                 assert!(update_add_htlcs.is_empty());
6907                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6908                                 assert!(update_fail_htlcs.is_empty());
6909                                 assert!(update_fail_malformed_htlcs.is_empty());
6910                                 assert!(update_fee.is_none());
6911                                 update_fulfill_htlcs[0].clone()
6912                         },
6913                         _ => panic!("Unexpected event"),
6914                 }
6915         };
6916
6917         update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6918
6919         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6920
6921         assert!(nodes[0].node.list_channels().is_empty());
6922         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6923         assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6924         check_added_monitors!(nodes[0], 1);
6925         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6926 }
6927
6928 #[test]
6929 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6930         //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.
6931
6932         let chanmon_cfgs = create_chanmon_cfgs(2);
6933         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6934         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6935         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6936         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6937
6938         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6939         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6940         check_added_monitors!(nodes[0], 1);
6941
6942         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6943         updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6944
6945         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6946         check_added_monitors!(nodes[1], 0);
6947         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6948
6949         let events = nodes[1].node.get_and_clear_pending_msg_events();
6950
6951         let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6952                 match events[0] {
6953                         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, .. } } => {
6954                                 assert!(update_add_htlcs.is_empty());
6955                                 assert!(update_fulfill_htlcs.is_empty());
6956                                 assert!(update_fail_htlcs.is_empty());
6957                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6958                                 assert!(update_fee.is_none());
6959                                 update_fail_malformed_htlcs[0].clone()
6960                         },
6961                         _ => panic!("Unexpected event"),
6962                 }
6963         };
6964         update_msg.failure_code &= !0x8000;
6965         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6966
6967         assert!(nodes[0].node.list_channels().is_empty());
6968         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6969         assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6970         check_added_monitors!(nodes[0], 1);
6971         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6972 }
6973
6974 #[test]
6975 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6976         //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6977         //    * 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.
6978
6979         let chanmon_cfgs = create_chanmon_cfgs(3);
6980         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6981         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6982         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6983         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6984         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6985
6986         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
6987
6988         //First hop
6989         let mut payment_event = {
6990                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6991                 check_added_monitors!(nodes[0], 1);
6992                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6993                 assert_eq!(events.len(), 1);
6994                 SendEvent::from_event(events.remove(0))
6995         };
6996         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6997         check_added_monitors!(nodes[1], 0);
6998         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6999         expect_pending_htlcs_forwardable!(nodes[1]);
7000         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7001         assert_eq!(events_2.len(), 1);
7002         check_added_monitors!(nodes[1], 1);
7003         payment_event = SendEvent::from_event(events_2.remove(0));
7004         assert_eq!(payment_event.msgs.len(), 1);
7005
7006         //Second Hop
7007         payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
7008         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
7009         check_added_monitors!(nodes[2], 0);
7010         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
7011
7012         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
7013         assert_eq!(events_3.len(), 1);
7014         let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
7015                 match events_3[0] {
7016                         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 } } => {
7017                                 assert!(update_add_htlcs.is_empty());
7018                                 assert!(update_fulfill_htlcs.is_empty());
7019                                 assert!(update_fail_htlcs.is_empty());
7020                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
7021                                 assert!(update_fee.is_none());
7022                                 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
7023                         },
7024                         _ => panic!("Unexpected event"),
7025                 }
7026         };
7027
7028         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
7029
7030         check_added_monitors!(nodes[1], 0);
7031         commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
7032         expect_pending_htlcs_forwardable!(nodes[1]);
7033         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
7034         assert_eq!(events_4.len(), 1);
7035
7036         //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
7037         match events_4[0] {
7038                 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, .. } } => {
7039                         assert!(update_add_htlcs.is_empty());
7040                         assert!(update_fulfill_htlcs.is_empty());
7041                         assert_eq!(update_fail_htlcs.len(), 1);
7042                         assert!(update_fail_malformed_htlcs.is_empty());
7043                         assert!(update_fee.is_none());
7044                 },
7045                 _ => panic!("Unexpected event"),
7046         };
7047
7048         check_added_monitors!(nodes[1], 1);
7049 }
7050
7051 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
7052         // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
7053         // 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
7054         // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
7055
7056         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7057         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7058         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7059         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7060         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7061         let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7062
7063         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7064
7065         // We route 2 dust-HTLCs between A and B
7066         let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7067         let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7068         route_payment(&nodes[0], &[&nodes[1]], 1000000);
7069
7070         // Cache one local commitment tx as previous
7071         let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7072
7073         // Fail one HTLC to prune it in the will-be-latest-local commitment tx
7074         assert!(nodes[1].node.fail_htlc_backwards(&payment_hash_2));
7075         check_added_monitors!(nodes[1], 0);
7076         expect_pending_htlcs_forwardable!(nodes[1]);
7077         check_added_monitors!(nodes[1], 1);
7078
7079         let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7080         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
7081         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
7082         check_added_monitors!(nodes[0], 1);
7083
7084         // Cache one local commitment tx as lastest
7085         let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7086
7087         let events = nodes[0].node.get_and_clear_pending_msg_events();
7088         match events[0] {
7089                 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
7090                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7091                 },
7092                 _ => panic!("Unexpected event"),
7093         }
7094         match events[1] {
7095                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
7096                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7097                 },
7098                 _ => panic!("Unexpected event"),
7099         }
7100
7101         assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
7102         // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7103         if announce_latest {
7104                 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
7105         } else {
7106                 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
7107         }
7108
7109         check_closed_broadcast!(nodes[0], true);
7110         check_added_monitors!(nodes[0], 1);
7111         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7112
7113         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7114         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7115         let events = nodes[0].node.get_and_clear_pending_events();
7116         // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
7117         assert_eq!(events.len(), 2);
7118         let mut first_failed = false;
7119         for event in events {
7120                 match event {
7121                         Event::PaymentPathFailed { payment_hash, .. } => {
7122                                 if payment_hash == payment_hash_1 {
7123                                         assert!(!first_failed);
7124                                         first_failed = true;
7125                                 } else {
7126                                         assert_eq!(payment_hash, payment_hash_2);
7127                                 }
7128                         }
7129                         _ => panic!("Unexpected event"),
7130                 }
7131         }
7132 }
7133
7134 #[test]
7135 fn test_failure_delay_dust_htlc_local_commitment() {
7136         do_test_failure_delay_dust_htlc_local_commitment(true);
7137         do_test_failure_delay_dust_htlc_local_commitment(false);
7138 }
7139
7140 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7141         // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7142         // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7143         // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7144         // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7145         // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7146         // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7147
7148         let chanmon_cfgs = create_chanmon_cfgs(3);
7149         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7150         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7151         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7152         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7153
7154         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7155
7156         let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7157         let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7158
7159         let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7160         let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7161
7162         // We revoked bs_commitment_tx
7163         if revoked {
7164                 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7165                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
7166         }
7167
7168         let mut timeout_tx = Vec::new();
7169         if local {
7170                 // We fail dust-HTLC 1 by broadcast of local commitment tx
7171                 mine_transaction(&nodes[0], &as_commitment_tx[0]);
7172                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7173                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7174                 expect_payment_failed!(nodes[0], dust_hash, true);
7175
7176                 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
7177                 check_closed_broadcast!(nodes[0], true);
7178                 check_added_monitors!(nodes[0], 1);
7179                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7180                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
7181                 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7182                 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7183                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7184                 mine_transaction(&nodes[0], &timeout_tx[0]);
7185                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7186                 expect_payment_failed!(nodes[0], non_dust_hash, true);
7187         } else {
7188                 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7189                 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
7190                 check_closed_broadcast!(nodes[0], true);
7191                 check_added_monitors!(nodes[0], 1);
7192                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7193                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7194                 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7195                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
7196                 if !revoked {
7197                         expect_payment_failed!(nodes[0], dust_hash, true);
7198                         assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7199                         // We fail non-dust-HTLC 2 by broadcast of local timeout tx on remote commitment tx
7200                         mine_transaction(&nodes[0], &timeout_tx[0]);
7201                         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7202                         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7203                         expect_payment_failed!(nodes[0], non_dust_hash, true);
7204                 } else {
7205                         // If revoked, both dust & non-dust HTLCs should have been failed after ANTI_REORG_DELAY confs of revoked
7206                         // commitment tx
7207                         let events = nodes[0].node.get_and_clear_pending_events();
7208                         assert_eq!(events.len(), 2);
7209                         let first;
7210                         match events[0] {
7211                                 Event::PaymentPathFailed { payment_hash, .. } => {
7212                                         if payment_hash == dust_hash { first = true; }
7213                                         else { first = false; }
7214                                 },
7215                                 _ => panic!("Unexpected event"),
7216                         }
7217                         match events[1] {
7218                                 Event::PaymentPathFailed { payment_hash, .. } => {
7219                                         if first { assert_eq!(payment_hash, non_dust_hash); }
7220                                         else { assert_eq!(payment_hash, dust_hash); }
7221                                 },
7222                                 _ => panic!("Unexpected event"),
7223                         }
7224                 }
7225         }
7226 }
7227
7228 #[test]
7229 fn test_sweep_outbound_htlc_failure_update() {
7230         do_test_sweep_outbound_htlc_failure_update(false, true);
7231         do_test_sweep_outbound_htlc_failure_update(false, false);
7232         do_test_sweep_outbound_htlc_failure_update(true, false);
7233 }
7234
7235 #[test]
7236 fn test_user_configurable_csv_delay() {
7237         // We test our channel constructors yield errors when we pass them absurd csv delay
7238
7239         let mut low_our_to_self_config = UserConfig::default();
7240         low_our_to_self_config.own_channel_config.our_to_self_delay = 6;
7241         let mut high_their_to_self_config = UserConfig::default();
7242         high_their_to_self_config.peer_channel_config_limits.their_to_self_delay = 100;
7243         let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7244         let chanmon_cfgs = create_chanmon_cfgs(2);
7245         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7246         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7247         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7248
7249         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7250         if let Err(error) = Channel::new_outbound(&&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) },
7251                 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), 1000000, 1000000, 0,
7252                 &low_our_to_self_config, 0, 42)
7253         {
7254                 match error {
7255                         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())); },
7256                         _ => panic!("Unexpected event"),
7257                 }
7258         } else { assert!(false) }
7259
7260         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7261         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7262         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7263         open_channel.to_self_delay = 200;
7264         if let Err(error) = Channel::new_from_req(&&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) },
7265                 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), &open_channel, 0,
7266                 &low_our_to_self_config, 0, &nodes[0].logger, 42)
7267         {
7268                 match error {
7269                         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()));  },
7270                         _ => panic!("Unexpected event"),
7271                 }
7272         } else { assert!(false); }
7273
7274         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7275         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7276         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()));
7277         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7278         accept_channel.to_self_delay = 200;
7279         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7280         let reason_msg;
7281         if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7282                 match action {
7283                         &ErrorAction::SendErrorMessage { ref msg } => {
7284                                 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()));
7285                                 reason_msg = msg.data.clone();
7286                         },
7287                         _ => { panic!(); }
7288                 }
7289         } else { panic!(); }
7290         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg });
7291
7292         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7293         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7294         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7295         open_channel.to_self_delay = 200;
7296         if let Err(error) = Channel::new_from_req(&&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) },
7297                 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), &open_channel, 0,
7298                 &high_their_to_self_config, 0, &nodes[0].logger, 42)
7299         {
7300                 match error {
7301                         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())); },
7302                         _ => panic!("Unexpected event"),
7303                 }
7304         } else { assert!(false); }
7305 }
7306
7307 #[test]
7308 fn test_data_loss_protect() {
7309         // We want to be sure that :
7310         // * we don't broadcast our Local Commitment Tx in case of fallen behind
7311         //   (but this is not quite true - we broadcast during Drop because chanmon is out of sync with chanmgr)
7312         // * we close channel in case of detecting other being fallen behind
7313         // * we are able to claim our own outputs thanks to to_remote being static
7314         // TODO: this test is incomplete and the data_loss_protect implementation is incomplete - see issue #775
7315         let persister;
7316         let logger;
7317         let fee_estimator;
7318         let tx_broadcaster;
7319         let chain_source;
7320         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7321         // We broadcast during Drop because chanmon is out of sync with chanmgr, which would cause a panic
7322         // during signing due to revoked tx
7323         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7324         let keys_manager = &chanmon_cfgs[0].keys_manager;
7325         let monitor;
7326         let node_state_0;
7327         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7328         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7329         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7330
7331         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7332
7333         // Cache node A state before any channel update
7334         let previous_node_state = nodes[0].node.encode();
7335         let mut previous_chain_monitor_state = test_utils::TestVecWriter(Vec::new());
7336         get_monitor!(nodes[0], chan.2).write(&mut previous_chain_monitor_state).unwrap();
7337
7338         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7339         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7340
7341         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7342         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7343
7344         // Restore node A from previous state
7345         logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7346         let mut chain_monitor = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut io::Cursor::new(previous_chain_monitor_state.0), keys_manager).unwrap().1;
7347         chain_source = test_utils::TestChainSource::new(Network::Testnet);
7348         tx_broadcaster = test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new()), blocks: Arc::new(Mutex::new(Vec::new()))};
7349         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
7350         persister = test_utils::TestPersister::new();
7351         monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &tx_broadcaster, &logger, &fee_estimator, &persister, keys_manager);
7352         node_state_0 = {
7353                 let mut channel_monitors = HashMap::new();
7354                 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chain_monitor);
7355                 <(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 {
7356                         keys_manager: keys_manager,
7357                         fee_estimator: &fee_estimator,
7358                         chain_monitor: &monitor,
7359                         logger: &logger,
7360                         tx_broadcaster: &tx_broadcaster,
7361                         default_config: UserConfig::default(),
7362                         channel_monitors,
7363                 }).unwrap().1
7364         };
7365         nodes[0].node = &node_state_0;
7366         assert!(monitor.watch_channel(OutPoint { txid: chan.3.txid(), index: 0 }, chain_monitor).is_ok());
7367         nodes[0].chain_monitor = &monitor;
7368         nodes[0].chain_source = &chain_source;
7369
7370         check_added_monitors!(nodes[0], 1);
7371
7372         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7373         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7374
7375         let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7376
7377         // Check we don't broadcast any transactions following learning of per_commitment_point from B
7378         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7379         check_added_monitors!(nodes[0], 1);
7380
7381         {
7382                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7383                 assert_eq!(node_txn.len(), 0);
7384         }
7385
7386         let mut reestablish_1 = Vec::with_capacity(1);
7387         for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7388                 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
7389                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7390                         reestablish_1.push(msg.clone());
7391                 } else if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7392                 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7393                         match action {
7394                                 &ErrorAction::SendErrorMessage { ref msg } => {
7395                                         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");
7396                                 },
7397                                 _ => panic!("Unexpected event!"),
7398                         }
7399                 } else {
7400                         panic!("Unexpected event")
7401                 }
7402         }
7403
7404         // Check we close channel detecting A is fallen-behind
7405         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7406         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Peer attempted to reestablish channel with a very old local commitment transaction".to_string() });
7407         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Peer attempted to reestablish channel with a very old local commitment transaction");
7408         check_added_monitors!(nodes[1], 1);
7409
7410         // Check A is able to claim to_remote output
7411         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7412         assert_eq!(node_txn.len(), 1);
7413         check_spends!(node_txn[0], chan.3);
7414         assert_eq!(node_txn[0].output.len(), 2);
7415         mine_transaction(&nodes[0], &node_txn[0]);
7416         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7417         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { 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".to_string() });
7418         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
7419         assert_eq!(spend_txn.len(), 1);
7420         check_spends!(spend_txn[0], node_txn[0]);
7421 }
7422
7423 #[test]
7424 fn test_check_htlc_underpaying() {
7425         // Send payment through A -> B but A is maliciously
7426         // sending a probe payment (i.e less than expected value0
7427         // to B, B should refuse payment.
7428
7429         let chanmon_cfgs = create_chanmon_cfgs(2);
7430         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7431         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7432         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7433
7434         // Create some initial channels
7435         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7436
7437         let scorer = test_utils::TestScorer::with_penalty(0);
7438         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7439         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7440         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();
7441         let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7442         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200).unwrap();
7443         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7444         check_added_monitors!(nodes[0], 1);
7445
7446         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7447         assert_eq!(events.len(), 1);
7448         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7449         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7450         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7451
7452         // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7453         // and then will wait a second random delay before failing the HTLC back:
7454         expect_pending_htlcs_forwardable!(nodes[1]);
7455         expect_pending_htlcs_forwardable!(nodes[1]);
7456
7457         // Node 3 is expecting payment of 100_000 but received 10_000,
7458         // it should fail htlc like we didn't know the preimage.
7459         nodes[1].node.process_pending_htlc_forwards();
7460
7461         let events = nodes[1].node.get_and_clear_pending_msg_events();
7462         assert_eq!(events.len(), 1);
7463         let (update_fail_htlc, commitment_signed) = match events[0] {
7464                 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 } } => {
7465                         assert!(update_add_htlcs.is_empty());
7466                         assert!(update_fulfill_htlcs.is_empty());
7467                         assert_eq!(update_fail_htlcs.len(), 1);
7468                         assert!(update_fail_malformed_htlcs.is_empty());
7469                         assert!(update_fee.is_none());
7470                         (update_fail_htlcs[0].clone(), commitment_signed)
7471                 },
7472                 _ => panic!("Unexpected event"),
7473         };
7474         check_added_monitors!(nodes[1], 1);
7475
7476         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7477         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7478
7479         // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7480         let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7481         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(CHAN_CONFIRM_DEPTH));
7482         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7483 }
7484
7485 #[test]
7486 fn test_announce_disable_channels() {
7487         // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7488         // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7489
7490         let chanmon_cfgs = create_chanmon_cfgs(2);
7491         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7492         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7493         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7494
7495         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7496         create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::known(), InitFeatures::known());
7497         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7498
7499         // Disconnect peers
7500         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7501         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7502
7503         nodes[0].node.timer_tick_occurred(); // Enabled -> DisabledStaged
7504         nodes[0].node.timer_tick_occurred(); // DisabledStaged -> Disabled
7505         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7506         assert_eq!(msg_events.len(), 3);
7507         let mut chans_disabled = HashMap::new();
7508         for e in msg_events {
7509                 match e {
7510                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7511                                 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7512                                 // Check that each channel gets updated exactly once
7513                                 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7514                                         panic!("Generated ChannelUpdate for wrong chan!");
7515                                 }
7516                         },
7517                         _ => panic!("Unexpected event"),
7518                 }
7519         }
7520         // Reconnect peers
7521         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7522         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7523         assert_eq!(reestablish_1.len(), 3);
7524         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7525         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7526         assert_eq!(reestablish_2.len(), 3);
7527
7528         // Reestablish chan_1
7529         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7530         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7531         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7532         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7533         // Reestablish chan_2
7534         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7535         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7536         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7537         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7538         // Reestablish chan_3
7539         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7540         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7541         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7542         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7543
7544         nodes[0].node.timer_tick_occurred();
7545         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7546         nodes[0].node.timer_tick_occurred();
7547         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7548         assert_eq!(msg_events.len(), 3);
7549         for e in msg_events {
7550                 match e {
7551                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7552                                 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7553                                 match chans_disabled.remove(&msg.contents.short_channel_id) {
7554                                         // Each update should have a higher timestamp than the previous one, replacing
7555                                         // the old one.
7556                                         Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7557                                         None => panic!("Generated ChannelUpdate for wrong chan!"),
7558                                 }
7559                         },
7560                         _ => panic!("Unexpected event"),
7561                 }
7562         }
7563         // Check that each channel gets updated exactly once
7564         assert!(chans_disabled.is_empty());
7565 }
7566
7567 #[test]
7568 fn test_bump_penalty_txn_on_revoked_commitment() {
7569         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7570         // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7571
7572         let chanmon_cfgs = create_chanmon_cfgs(2);
7573         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7574         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7575         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7576
7577         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7578
7579         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7580         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id())
7581                 .with_features(InvoiceFeatures::known());
7582         let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000, 30);
7583         send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7584
7585         let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7586         // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7587         assert_eq!(revoked_txn[0].output.len(), 4);
7588         assert_eq!(revoked_txn[0].input.len(), 1);
7589         assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7590         let revoked_txid = revoked_txn[0].txid();
7591
7592         let mut penalty_sum = 0;
7593         for outp in revoked_txn[0].output.iter() {
7594                 if outp.script_pubkey.is_v0_p2wsh() {
7595                         penalty_sum += outp.value;
7596                 }
7597         }
7598
7599         // Connect blocks to change height_timer range to see if we use right soonest_timelock
7600         let header_114 = connect_blocks(&nodes[1], 14);
7601
7602         // Actually revoke tx by claiming a HTLC
7603         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7604         let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7605         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] });
7606         check_added_monitors!(nodes[1], 1);
7607
7608         // One or more justice tx should have been broadcast, check it
7609         let penalty_1;
7610         let feerate_1;
7611         {
7612                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7613                 assert_eq!(node_txn.len(), 2); // justice tx (broadcasted from ChannelMonitor) + local commitment tx
7614                 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7615                 assert_eq!(node_txn[0].output.len(), 1);
7616                 check_spends!(node_txn[0], revoked_txn[0]);
7617                 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7618                 feerate_1 = fee_1 * 1000 / node_txn[0].get_weight() as u64;
7619                 penalty_1 = node_txn[0].txid();
7620                 node_txn.clear();
7621         };
7622
7623         // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7624         connect_blocks(&nodes[1], 15);
7625         let mut penalty_2 = penalty_1;
7626         let mut feerate_2 = 0;
7627         {
7628                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7629                 assert_eq!(node_txn.len(), 1);
7630                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7631                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7632                         assert_eq!(node_txn[0].output.len(), 1);
7633                         check_spends!(node_txn[0], revoked_txn[0]);
7634                         penalty_2 = node_txn[0].txid();
7635                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7636                         assert_ne!(penalty_2, penalty_1);
7637                         let fee_2 = penalty_sum - node_txn[0].output[0].value;
7638                         feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7639                         // Verify 25% bump heuristic
7640                         assert!(feerate_2 * 100 >= feerate_1 * 125);
7641                         node_txn.clear();
7642                 }
7643         }
7644         assert_ne!(feerate_2, 0);
7645
7646         // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7647         connect_blocks(&nodes[1], 1);
7648         let penalty_3;
7649         let mut feerate_3 = 0;
7650         {
7651                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7652                 assert_eq!(node_txn.len(), 1);
7653                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7654                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7655                         assert_eq!(node_txn[0].output.len(), 1);
7656                         check_spends!(node_txn[0], revoked_txn[0]);
7657                         penalty_3 = node_txn[0].txid();
7658                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7659                         assert_ne!(penalty_3, penalty_2);
7660                         let fee_3 = penalty_sum - node_txn[0].output[0].value;
7661                         feerate_3 = fee_3 * 1000 / node_txn[0].get_weight() as u64;
7662                         // Verify 25% bump heuristic
7663                         assert!(feerate_3 * 100 >= feerate_2 * 125);
7664                         node_txn.clear();
7665                 }
7666         }
7667         assert_ne!(feerate_3, 0);
7668
7669         nodes[1].node.get_and_clear_pending_events();
7670         nodes[1].node.get_and_clear_pending_msg_events();
7671 }
7672
7673 #[test]
7674 fn test_bump_penalty_txn_on_revoked_htlcs() {
7675         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7676         // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7677
7678         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7679         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7680         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7681         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7682         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7683
7684         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7685         // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7686         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7687         let scorer = test_utils::TestScorer::with_penalty(0);
7688         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7689         let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None,
7690                 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7691         let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7692         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7693         let route = get_route(&nodes[1].node.get_our_node_id(), &payment_params, &nodes[1].network_graph.read_only(), None,
7694                 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7695         send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7696
7697         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7698         assert_eq!(revoked_local_txn[0].input.len(), 1);
7699         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7700
7701         // Revoke local commitment tx
7702         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7703
7704         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7705         // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7706         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] });
7707         check_closed_broadcast!(nodes[1], true);
7708         check_added_monitors!(nodes[1], 1);
7709         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7710         connect_blocks(&nodes[1], 49); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7711
7712         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7713         assert_eq!(revoked_htlc_txn.len(), 3);
7714         check_spends!(revoked_htlc_txn[1], chan.3);
7715
7716         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7717         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7718         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7719
7720         assert_eq!(revoked_htlc_txn[2].input.len(), 1);
7721         assert_eq!(revoked_htlc_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7722         assert_eq!(revoked_htlc_txn[2].output.len(), 1);
7723         check_spends!(revoked_htlc_txn[2], revoked_local_txn[0]);
7724
7725         // Broadcast set of revoked txn on A
7726         let hash_128 = connect_blocks(&nodes[0], 40);
7727         let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7728         connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] });
7729         let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7730         connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[2].clone()] });
7731         let events = nodes[0].node.get_and_clear_pending_events();
7732         expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7733         match events[1] {
7734                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7735                 _ => panic!("Unexpected event"),
7736         }
7737         let first;
7738         let feerate_1;
7739         let penalty_txn;
7740         {
7741                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7742                 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7743                 // Verify claim tx are spending revoked HTLC txn
7744
7745                 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7746                 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7747                 // which are included in the same block (they are broadcasted because we scan the
7748                 // transactions linearly and generate claims as we go, they likely should be removed in the
7749                 // future).
7750                 assert_eq!(node_txn[0].input.len(), 1);
7751                 check_spends!(node_txn[0], revoked_local_txn[0]);
7752                 assert_eq!(node_txn[1].input.len(), 1);
7753                 check_spends!(node_txn[1], revoked_local_txn[0]);
7754                 assert_eq!(node_txn[2].input.len(), 1);
7755                 check_spends!(node_txn[2], revoked_local_txn[0]);
7756
7757                 // Each of the three justice transactions claim a separate (single) output of the three
7758                 // available, which we check here:
7759                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7760                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7761                 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7762
7763                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7764                 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7765
7766                 // node_txn[3] is the local commitment tx broadcast just because (and somewhat in case of
7767                 // reorgs, though its not clear its ever worth broadcasting conflicting txn like this when
7768                 // a remote commitment tx has already been confirmed).
7769                 check_spends!(node_txn[3], chan.3);
7770
7771                 // node_txn[4] spends the revoked outputs from the revoked_htlc_txn (which only have one
7772                 // output, checked above).
7773                 assert_eq!(node_txn[4].input.len(), 2);
7774                 assert_eq!(node_txn[4].output.len(), 1);
7775                 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7776
7777                 first = node_txn[4].txid();
7778                 // Store both feerates for later comparison
7779                 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[4].output[0].value;
7780                 feerate_1 = fee_1 * 1000 / node_txn[4].get_weight() as u64;
7781                 penalty_txn = vec![node_txn[2].clone()];
7782                 node_txn.clear();
7783         }
7784
7785         // Connect one more block to see if bumped penalty are issued for HTLC txn
7786         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7787         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7788         let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7789         connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() });
7790         {
7791                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7792                 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7793
7794                 check_spends!(node_txn[0], revoked_local_txn[0]);
7795                 check_spends!(node_txn[1], revoked_local_txn[0]);
7796                 // Note that these are both bogus - they spend outputs already claimed in block 129:
7797                 if node_txn[0].input[0].previous_output == revoked_htlc_txn[0].input[0].previous_output  {
7798                         assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7799                 } else {
7800                         assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7801                         assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7802                 }
7803
7804                 node_txn.clear();
7805         };
7806
7807         // Few more blocks to confirm penalty txn
7808         connect_blocks(&nodes[0], 4);
7809         assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7810         let header_144 = connect_blocks(&nodes[0], 9);
7811         let node_txn = {
7812                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7813                 assert_eq!(node_txn.len(), 1);
7814
7815                 assert_eq!(node_txn[0].input.len(), 2);
7816                 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7817                 // Verify bumped tx is different and 25% bump heuristic
7818                 assert_ne!(first, node_txn[0].txid());
7819                 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[0].output[0].value;
7820                 let feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7821                 assert!(feerate_2 * 100 > feerate_1 * 125);
7822                 let txn = vec![node_txn[0].clone()];
7823                 node_txn.clear();
7824                 txn
7825         };
7826         // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7827         let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7828         connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn });
7829         connect_blocks(&nodes[0], 20);
7830         {
7831                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7832                 // We verify than no new transaction has been broadcast because previously
7833                 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7834                 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7835                 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7836                 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7837                 // up bumped justice generation.
7838                 assert_eq!(node_txn.len(), 0);
7839                 node_txn.clear();
7840         }
7841         check_closed_broadcast!(nodes[0], true);
7842         check_added_monitors!(nodes[0], 1);
7843 }
7844
7845 #[test]
7846 fn test_bump_penalty_txn_on_remote_commitment() {
7847         // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7848         // we're able to claim outputs on remote commitment transaction before timelocks expiration
7849
7850         // Create 2 HTLCs
7851         // Provide preimage for one
7852         // Check aggregation
7853
7854         let chanmon_cfgs = create_chanmon_cfgs(2);
7855         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7856         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7857         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7858
7859         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7860         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7861         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7862
7863         // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7864         let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7865         assert_eq!(remote_txn[0].output.len(), 4);
7866         assert_eq!(remote_txn[0].input.len(), 1);
7867         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7868
7869         // Claim a HTLC without revocation (provide B monitor with preimage)
7870         nodes[1].node.claim_funds(payment_preimage);
7871         mine_transaction(&nodes[1], &remote_txn[0]);
7872         check_added_monitors!(nodes[1], 2);
7873         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7874
7875         // One or more claim tx should have been broadcast, check it
7876         let timeout;
7877         let preimage;
7878         let preimage_bump;
7879         let feerate_timeout;
7880         let feerate_preimage;
7881         {
7882                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7883                 // 9 transactions including:
7884                 // 1*2 ChannelManager local broadcasts of commitment + HTLC-Success
7885                 // 1*3 ChannelManager local broadcasts of commitment + HTLC-Success + HTLC-Timeout
7886                 // 2 * HTLC-Success (one RBF bump we'll check later)
7887                 // 1 * HTLC-Timeout
7888                 assert_eq!(node_txn.len(), 8);
7889                 assert_eq!(node_txn[0].input.len(), 1);
7890                 assert_eq!(node_txn[6].input.len(), 1);
7891                 check_spends!(node_txn[0], remote_txn[0]);
7892                 check_spends!(node_txn[6], remote_txn[0]);
7893                 assert_eq!(node_txn[0].input[0].previous_output, node_txn[3].input[0].previous_output);
7894                 preimage_bump = node_txn[3].clone();
7895
7896                 check_spends!(node_txn[1], chan.3);
7897                 check_spends!(node_txn[2], node_txn[1]);
7898                 assert_eq!(node_txn[1], node_txn[4]);
7899                 assert_eq!(node_txn[2], node_txn[5]);
7900
7901                 timeout = node_txn[6].txid();
7902                 let index = node_txn[6].input[0].previous_output.vout;
7903                 let fee = remote_txn[0].output[index as usize].value - node_txn[6].output[0].value;
7904                 feerate_timeout = fee * 1000 / node_txn[6].get_weight() as u64;
7905
7906                 preimage = node_txn[0].txid();
7907                 let index = node_txn[0].input[0].previous_output.vout;
7908                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7909                 feerate_preimage = fee * 1000 / node_txn[0].get_weight() as u64;
7910
7911                 node_txn.clear();
7912         };
7913         assert_ne!(feerate_timeout, 0);
7914         assert_ne!(feerate_preimage, 0);
7915
7916         // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7917         connect_blocks(&nodes[1], 15);
7918         {
7919                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7920                 assert_eq!(node_txn.len(), 1);
7921                 assert_eq!(node_txn[0].input.len(), 1);
7922                 assert_eq!(preimage_bump.input.len(), 1);
7923                 check_spends!(node_txn[0], remote_txn[0]);
7924                 check_spends!(preimage_bump, remote_txn[0]);
7925
7926                 let index = preimage_bump.input[0].previous_output.vout;
7927                 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
7928                 let new_feerate = fee * 1000 / preimage_bump.get_weight() as u64;
7929                 assert!(new_feerate * 100 > feerate_timeout * 125);
7930                 assert_ne!(timeout, preimage_bump.txid());
7931
7932                 let index = node_txn[0].input[0].previous_output.vout;
7933                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7934                 let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
7935                 assert!(new_feerate * 100 > feerate_preimage * 125);
7936                 assert_ne!(preimage, node_txn[0].txid());
7937
7938                 node_txn.clear();
7939         }
7940
7941         nodes[1].node.get_and_clear_pending_events();
7942         nodes[1].node.get_and_clear_pending_msg_events();
7943 }
7944
7945 #[test]
7946 fn test_counterparty_raa_skip_no_crash() {
7947         // Previously, if our counterparty sent two RAAs in a row without us having provided a
7948         // commitment transaction, we would have happily carried on and provided them the next
7949         // commitment transaction based on one RAA forward. This would probably eventually have led to
7950         // channel closure, but it would not have resulted in funds loss. Still, our
7951         // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
7952         // check simply that the channel is closed in response to such an RAA, but don't check whether
7953         // we decide to punish our counterparty for revoking their funds (as we don't currently
7954         // implement that).
7955         let chanmon_cfgs = create_chanmon_cfgs(2);
7956         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7957         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7958         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7959         let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
7960
7961         let mut guard = nodes[0].node.channel_state.lock().unwrap();
7962         let keys = guard.by_id.get_mut(&channel_id).unwrap().get_signer();
7963
7964         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7965
7966         // Make signer believe we got a counterparty signature, so that it allows the revocation
7967         keys.get_enforcement_state().last_holder_commitment -= 1;
7968         let per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
7969
7970         // Must revoke without gaps
7971         keys.get_enforcement_state().last_holder_commitment -= 1;
7972         keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
7973
7974         keys.get_enforcement_state().last_holder_commitment -= 1;
7975         let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7976                 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7977
7978         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7979                 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
7980         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7981         check_added_monitors!(nodes[1], 1);
7982         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
7983 }
7984
7985 #[test]
7986 fn test_bump_txn_sanitize_tracking_maps() {
7987         // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7988         // verify we clean then right after expiration of ANTI_REORG_DELAY.
7989
7990         let chanmon_cfgs = create_chanmon_cfgs(2);
7991         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7992         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7993         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7994
7995         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7996         // Lock HTLC in both directions
7997         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
7998         route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
7999
8000         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
8001         assert_eq!(revoked_local_txn[0].input.len(), 1);
8002         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8003
8004         // Revoke local commitment tx
8005         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
8006
8007         // Broadcast set of revoked txn on A
8008         connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
8009         expect_pending_htlcs_forwardable_ignore!(nodes[0]);
8010         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
8011
8012         mine_transaction(&nodes[0], &revoked_local_txn[0]);
8013         check_closed_broadcast!(nodes[0], true);
8014         check_added_monitors!(nodes[0], 1);
8015         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8016         let penalty_txn = {
8017                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8018                 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
8019                 check_spends!(node_txn[0], revoked_local_txn[0]);
8020                 check_spends!(node_txn[1], revoked_local_txn[0]);
8021                 check_spends!(node_txn[2], revoked_local_txn[0]);
8022                 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
8023                 node_txn.clear();
8024                 penalty_txn
8025         };
8026         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8027         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
8028         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8029         {
8030                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
8031                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
8032                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
8033         }
8034 }
8035
8036 #[test]
8037 fn test_pending_claimed_htlc_no_balance_underflow() {
8038         // Tests that if we have a pending outbound HTLC as well as a claimed-but-not-fully-removed
8039         // HTLC we will not underflow when we call `Channel::get_balance_msat()`.
8040         let chanmon_cfgs = create_chanmon_cfgs(2);
8041         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8042         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8043         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8044         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
8045
8046         let payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 1_010_000).0;
8047         nodes[1].node.claim_funds(payment_preimage);
8048         check_added_monitors!(nodes[1], 1);
8049         let fulfill_ev = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8050
8051         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &fulfill_ev.update_fulfill_htlcs[0]);
8052         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
8053         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &fulfill_ev.commitment_signed);
8054         check_added_monitors!(nodes[0], 1);
8055         let (_raa, _cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
8056
8057         // At this point nodes[1] has received 1,010k msat (10k msat more than their reserve) and can
8058         // send an HTLC back (though it will go in the holding cell). Send an HTLC back and check we
8059         // can get our balance.
8060
8061         // Get a route from nodes[1] to nodes[0] by getting a route going the other way and then flip
8062         // the public key of the only hop. This works around ChannelDetails not showing the
8063         // almost-claimed HTLC as available balance.
8064         let (mut route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 10_000);
8065         route.payment_params = None; // This is all wrong, but unnecessary
8066         route.paths[0][0].pubkey = nodes[0].node.get_our_node_id();
8067         let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[0]);
8068         nodes[1].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
8069
8070         assert_eq!(nodes[1].node.list_channels()[0].balance_msat, 1_000_000);
8071 }
8072
8073 #[test]
8074 fn test_channel_conf_timeout() {
8075         // Tests that, for inbound channels, we give up on them if the funding transaction does not
8076         // confirm within 2016 blocks, as recommended by BOLT 2.
8077         let chanmon_cfgs = create_chanmon_cfgs(2);
8078         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8079         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8080         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8081
8082         let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000, InitFeatures::known(), InitFeatures::known());
8083
8084         // The outbound node should wait forever for confirmation:
8085         // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
8086         // copied here instead of directly referencing the constant.
8087         connect_blocks(&nodes[0], 2016);
8088         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8089
8090         // The inbound node should fail the channel after exactly 2016 blocks
8091         connect_blocks(&nodes[1], 2015);
8092         check_added_monitors!(nodes[1], 0);
8093         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8094
8095         connect_blocks(&nodes[1], 1);
8096         check_added_monitors!(nodes[1], 1);
8097         check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut);
8098         let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
8099         assert_eq!(close_ev.len(), 1);
8100         match close_ev[0] {
8101                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
8102                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8103                         assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
8104                 },
8105                 _ => panic!("Unexpected event"),
8106         }
8107 }
8108
8109 #[test]
8110 fn test_override_channel_config() {
8111         let chanmon_cfgs = create_chanmon_cfgs(2);
8112         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8113         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8114         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8115
8116         // Node0 initiates a channel to node1 using the override config.
8117         let mut override_config = UserConfig::default();
8118         override_config.own_channel_config.our_to_self_delay = 200;
8119
8120         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
8121
8122         // Assert the channel created by node0 is using the override config.
8123         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8124         assert_eq!(res.channel_flags, 0);
8125         assert_eq!(res.to_self_delay, 200);
8126 }
8127
8128 #[test]
8129 fn test_override_0msat_htlc_minimum() {
8130         let mut zero_config = UserConfig::default();
8131         zero_config.own_channel_config.our_htlc_minimum_msat = 0;
8132         let chanmon_cfgs = create_chanmon_cfgs(2);
8133         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8134         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
8135         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8136
8137         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
8138         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8139         assert_eq!(res.htlc_minimum_msat, 1);
8140
8141         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8142         let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8143         assert_eq!(res.htlc_minimum_msat, 1);
8144 }
8145
8146 #[test]
8147 fn test_manually_accept_inbound_channel_request() {
8148         let mut manually_accept_conf = UserConfig::default();
8149         manually_accept_conf.manually_accept_inbound_channels = true;
8150         let chanmon_cfgs = create_chanmon_cfgs(2);
8151         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8152         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8153         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8154
8155         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8156         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8157
8158         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8159
8160         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8161         // accepting the inbound channel request.
8162         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8163
8164         let events = nodes[1].node.get_and_clear_pending_events();
8165         match events[0] {
8166                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8167                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, 23).unwrap();
8168                 }
8169                 _ => panic!("Unexpected event"),
8170         }
8171
8172         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8173         assert_eq!(accept_msg_ev.len(), 1);
8174
8175         match accept_msg_ev[0] {
8176                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8177                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8178                 }
8179                 _ => panic!("Unexpected event"),
8180         }
8181
8182         nodes[1].node.force_close_channel(&temp_channel_id).unwrap();
8183
8184         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8185         assert_eq!(close_msg_ev.len(), 1);
8186
8187         let events = nodes[1].node.get_and_clear_pending_events();
8188         match events[0] {
8189                 Event::ChannelClosed { user_channel_id, .. } => {
8190                         assert_eq!(user_channel_id, 23);
8191                 }
8192                 _ => panic!("Unexpected event"),
8193         }
8194 }
8195
8196 #[test]
8197 fn test_manually_reject_inbound_channel_request() {
8198         let mut manually_accept_conf = UserConfig::default();
8199         manually_accept_conf.manually_accept_inbound_channels = true;
8200         let chanmon_cfgs = create_chanmon_cfgs(2);
8201         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8202         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8203         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8204
8205         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8206         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8207
8208         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8209
8210         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8211         // rejecting the inbound channel request.
8212         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8213
8214         let events = nodes[1].node.get_and_clear_pending_events();
8215         match events[0] {
8216                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8217                         nodes[1].node.force_close_channel(&temporary_channel_id).unwrap();
8218                 }
8219                 _ => panic!("Unexpected event"),
8220         }
8221
8222         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8223         assert_eq!(close_msg_ev.len(), 1);
8224
8225         match close_msg_ev[0] {
8226                 MessageSendEvent::HandleError { ref node_id, .. } => {
8227                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8228                 }
8229                 _ => panic!("Unexpected event"),
8230         }
8231         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
8232 }
8233
8234 #[test]
8235 fn test_reject_funding_before_inbound_channel_accepted() {
8236         // This tests that when `UserConfig::manually_accept_inbound_channels` is set to true, inbound
8237         // channels must to be manually accepted through `ChannelManager::accept_inbound_channel` by
8238         // the node operator before the counterparty sends a `FundingCreated` message. If a
8239         // `FundingCreated` message is received before the channel is accepted, it should be rejected
8240         // and the channel should be closed.
8241         let mut manually_accept_conf = UserConfig::default();
8242         manually_accept_conf.manually_accept_inbound_channels = true;
8243         let chanmon_cfgs = create_chanmon_cfgs(2);
8244         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8245         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8246         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8247
8248         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8249         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8250         let temp_channel_id = res.temporary_channel_id;
8251
8252         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8253
8254         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in the `msg_events`.
8255         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8256
8257         // Clear the `Event::OpenChannelRequest` event without responding to the request.
8258         nodes[1].node.get_and_clear_pending_events();
8259
8260         // Get the `AcceptChannel` message of `nodes[1]` without calling
8261         // `ChannelManager::accept_inbound_channel`, which generates a
8262         // `MessageSendEvent::SendAcceptChannel` event. The message is passed to `nodes[0]`
8263         // `handle_accept_channel`, which is required in order for `create_funding_transaction` to
8264         // succeed when `nodes[0]` is passed to it.
8265         {
8266                 let mut lock;
8267                 let channel = get_channel_ref!(&nodes[1], lock, temp_channel_id);
8268                 let accept_chan_msg = channel.get_accept_channel_message();
8269                 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8270         }
8271
8272         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], 100000, 42);
8273
8274         nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
8275         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8276
8277         // The `funding_created_msg` should be rejected by `nodes[1]` as it hasn't accepted the channel
8278         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8279
8280         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8281         assert_eq!(close_msg_ev.len(), 1);
8282
8283         let expected_err = "FundingCreated message received before the channel was accepted";
8284         match close_msg_ev[0] {
8285                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id, } => {
8286                         assert_eq!(msg.channel_id, temp_channel_id);
8287                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8288                         assert_eq!(msg.data, expected_err);
8289                 }
8290                 _ => panic!("Unexpected event"),
8291         }
8292
8293         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
8294 }
8295
8296 #[test]
8297 fn test_can_not_accept_inbound_channel_twice() {
8298         let mut manually_accept_conf = UserConfig::default();
8299         manually_accept_conf.manually_accept_inbound_channels = true;
8300         let chanmon_cfgs = create_chanmon_cfgs(2);
8301         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8302         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8303         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8304
8305         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8306         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8307
8308         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8309
8310         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8311         // accepting the inbound channel request.
8312         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8313
8314         let events = nodes[1].node.get_and_clear_pending_events();
8315         match events[0] {
8316                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8317                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, 0).unwrap();
8318                         let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, 0);
8319                         match api_res {
8320                                 Err(APIError::APIMisuseError { err }) => {
8321                                         assert_eq!(err, "The channel isn't currently awaiting to be accepted.");
8322                                 },
8323                                 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
8324                                 Err(_) => panic!("Unexpected Error"),
8325                         }
8326                 }
8327                 _ => panic!("Unexpected event"),
8328         }
8329
8330         // Ensure that the channel wasn't closed after attempting to accept it twice.
8331         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8332         assert_eq!(accept_msg_ev.len(), 1);
8333
8334         match accept_msg_ev[0] {
8335                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8336                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8337                 }
8338                 _ => panic!("Unexpected event"),
8339         }
8340 }
8341
8342 #[test]
8343 fn test_can_not_accept_unknown_inbound_channel() {
8344         let chanmon_cfg = create_chanmon_cfgs(1);
8345         let node_cfg = create_node_cfgs(1, &chanmon_cfg);
8346         let node_chanmgr = create_node_chanmgrs(1, &node_cfg, &[None]);
8347         let node = create_network(1, &node_cfg, &node_chanmgr)[0].node;
8348
8349         let unknown_channel_id = [0; 32];
8350         let api_res = node.accept_inbound_channel(&unknown_channel_id, 0);
8351         match api_res {
8352                 Err(APIError::ChannelUnavailable { err }) => {
8353                         assert_eq!(err, "Can't accept a channel that doesn't exist");
8354                 },
8355                 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
8356                 Err(_) => panic!("Unexpected Error"),
8357         }
8358 }
8359
8360 #[test]
8361 fn test_simple_mpp() {
8362         // Simple test of sending a multi-path payment.
8363         let chanmon_cfgs = create_chanmon_cfgs(4);
8364         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8365         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8366         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8367
8368         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8369         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8370         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8371         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8372
8373         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8374         let path = route.paths[0].clone();
8375         route.paths.push(path);
8376         route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8377         route.paths[0][0].short_channel_id = chan_1_id;
8378         route.paths[0][1].short_channel_id = chan_3_id;
8379         route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8380         route.paths[1][0].short_channel_id = chan_2_id;
8381         route.paths[1][1].short_channel_id = chan_4_id;
8382         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8383         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8384 }
8385
8386 #[test]
8387 fn test_preimage_storage() {
8388         // Simple test of payment preimage storage allowing no client-side storage to claim payments
8389         let chanmon_cfgs = create_chanmon_cfgs(2);
8390         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8391         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8392         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8393
8394         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8395
8396         {
8397                 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200).unwrap();
8398                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8399                 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8400                 check_added_monitors!(nodes[0], 1);
8401                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8402                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8403                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8404                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8405         }
8406         // Note that after leaving the above scope we have no knowledge of any arguments or return
8407         // values from previous calls.
8408         expect_pending_htlcs_forwardable!(nodes[1]);
8409         let events = nodes[1].node.get_and_clear_pending_events();
8410         assert_eq!(events.len(), 1);
8411         match events[0] {
8412                 Event::PaymentReceived { ref purpose, .. } => {
8413                         match &purpose {
8414                                 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
8415                                         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8416                                 },
8417                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
8418                         }
8419                 },
8420                 _ => panic!("Unexpected event"),
8421         }
8422 }
8423
8424 #[test]
8425 #[allow(deprecated)]
8426 fn test_secret_timeout() {
8427         // Simple test of payment secret storage time outs. After
8428         // `create_inbound_payment(_for_hash)_legacy` is removed, this test will be removed as well.
8429         let chanmon_cfgs = create_chanmon_cfgs(2);
8430         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8431         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8432         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8433
8434         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8435
8436         let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment_legacy(Some(100_000), 2).unwrap();
8437
8438         // We should fail to register the same payment hash twice, at least until we've connected a
8439         // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
8440         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8441                 assert_eq!(err, "Duplicate payment hash");
8442         } else { panic!(); }
8443         let mut block = {
8444                 let node_1_blocks = nodes[1].blocks.lock().unwrap();
8445                 Block {
8446                         header: BlockHeader {
8447                                 version: 0x2000000,
8448                                 prev_blockhash: node_1_blocks.last().unwrap().0.block_hash(),
8449                                 merkle_root: Default::default(),
8450                                 time: node_1_blocks.len() as u32 + 7200, bits: 42, nonce: 42 },
8451                         txdata: vec![],
8452                 }
8453         };
8454         connect_block(&nodes[1], &block);
8455         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8456                 assert_eq!(err, "Duplicate payment hash");
8457         } else { panic!(); }
8458
8459         // If we then connect the second block, we should be able to register the same payment hash
8460         // again (this time getting a new payment secret).
8461         block.header.prev_blockhash = block.header.block_hash();
8462         block.header.time += 1;
8463         connect_block(&nodes[1], &block);
8464         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2).unwrap();
8465         assert_ne!(payment_secret_1, our_payment_secret);
8466
8467         {
8468                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8469                 nodes[0].node.send_payment(&route, payment_hash, &Some(our_payment_secret)).unwrap();
8470                 check_added_monitors!(nodes[0], 1);
8471                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8472                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8473                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8474                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8475         }
8476         // Note that after leaving the above scope we have no knowledge of any arguments or return
8477         // values from previous calls.
8478         expect_pending_htlcs_forwardable!(nodes[1]);
8479         let events = nodes[1].node.get_and_clear_pending_events();
8480         assert_eq!(events.len(), 1);
8481         match events[0] {
8482                 Event::PaymentReceived { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret }, .. } => {
8483                         assert!(payment_preimage.is_none());
8484                         assert_eq!(payment_secret, our_payment_secret);
8485                         // We don't actually have the payment preimage with which to claim this payment!
8486                 },
8487                 _ => panic!("Unexpected event"),
8488         }
8489 }
8490
8491 #[test]
8492 fn test_bad_secret_hash() {
8493         // Simple test of unregistered payment hash/invalid payment secret handling
8494         let chanmon_cfgs = create_chanmon_cfgs(2);
8495         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8496         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8497         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8498
8499         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8500
8501         let random_payment_hash = PaymentHash([42; 32]);
8502         let random_payment_secret = PaymentSecret([43; 32]);
8503         let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2).unwrap();
8504         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8505
8506         // All the below cases should end up being handled exactly identically, so we macro the
8507         // resulting events.
8508         macro_rules! handle_unknown_invalid_payment_data {
8509                 () => {
8510                         check_added_monitors!(nodes[0], 1);
8511                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8512                         let payment_event = SendEvent::from_event(events.pop().unwrap());
8513                         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8514                         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8515
8516                         // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8517                         // again to process the pending backwards-failure of the HTLC
8518                         expect_pending_htlcs_forwardable!(nodes[1]);
8519                         expect_pending_htlcs_forwardable!(nodes[1]);
8520                         check_added_monitors!(nodes[1], 1);
8521
8522                         // We should fail the payment back
8523                         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8524                         match events.pop().unwrap() {
8525                                 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8526                                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8527                                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8528                                 },
8529                                 _ => panic!("Unexpected event"),
8530                         }
8531                 }
8532         }
8533
8534         let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8535         // Error data is the HTLC value (100,000) and current block height
8536         let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8537
8538         // Send a payment with the right payment hash but the wrong payment secret
8539         nodes[0].node.send_payment(&route, our_payment_hash, &Some(random_payment_secret)).unwrap();
8540         handle_unknown_invalid_payment_data!();
8541         expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8542
8543         // Send a payment with a random payment hash, but the right payment secret
8544         nodes[0].node.send_payment(&route, random_payment_hash, &Some(our_payment_secret)).unwrap();
8545         handle_unknown_invalid_payment_data!();
8546         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8547
8548         // Send a payment with a random payment hash and random payment secret
8549         nodes[0].node.send_payment(&route, random_payment_hash, &Some(random_payment_secret)).unwrap();
8550         handle_unknown_invalid_payment_data!();
8551         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8552 }
8553
8554 #[test]
8555 fn test_update_err_monitor_lockdown() {
8556         // Our monitor will lock update of local commitment transaction if a broadcastion condition
8557         // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8558         // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
8559         //
8560         // This scenario may happen in a watchtower setup, where watchtower process a block height
8561         // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8562         // commitment at same time.
8563
8564         let chanmon_cfgs = create_chanmon_cfgs(2);
8565         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8566         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8567         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8568
8569         // Create some initial channel
8570         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8571         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8572
8573         // Rebalance the network to generate htlc in the two directions
8574         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8575
8576         // Route a HTLC from node 0 to node 1 (but don't settle)
8577         let preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8578
8579         // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8580         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8581         let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8582         let persister = test_utils::TestPersister::new();
8583         let watchtower = {
8584                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8585                 let mut w = test_utils::TestVecWriter(Vec::new());
8586                 monitor.write(&mut w).unwrap();
8587                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8588                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8589                 assert!(new_monitor == *monitor);
8590                 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);
8591                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8592                 watchtower
8593         };
8594         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8595         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8596         // transaction lock time requirements here.
8597         chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (header, 0));
8598         watchtower.chain_monitor.block_connected(&Block { header, txdata: vec![] }, 200);
8599
8600         // Try to update ChannelMonitor
8601         assert!(nodes[1].node.claim_funds(preimage));
8602         check_added_monitors!(nodes[1], 1);
8603         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8604         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8605         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8606         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8607                 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8608                         if let Err(_) =  watchtower.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8609                         if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8610                 } else { assert!(false); }
8611         } else { assert!(false); };
8612         // Our local monitor is in-sync and hasn't processed yet timeout
8613         check_added_monitors!(nodes[0], 1);
8614         let events = nodes[0].node.get_and_clear_pending_events();
8615         assert_eq!(events.len(), 1);
8616 }
8617
8618 #[test]
8619 fn test_concurrent_monitor_claim() {
8620         // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8621         // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8622         // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8623         // state N+1 confirms. Alice claims output from state N+1.
8624
8625         let chanmon_cfgs = create_chanmon_cfgs(2);
8626         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8627         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8628         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8629
8630         // Create some initial channel
8631         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8632         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8633
8634         // Rebalance the network to generate htlc in the two directions
8635         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8636
8637         // Route a HTLC from node 0 to node 1 (but don't settle)
8638         route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8639
8640         // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8641         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8642         let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8643         let persister = test_utils::TestPersister::new();
8644         let watchtower_alice = {
8645                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8646                 let mut w = test_utils::TestVecWriter(Vec::new());
8647                 monitor.write(&mut w).unwrap();
8648                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8649                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8650                 assert!(new_monitor == *monitor);
8651                 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);
8652                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8653                 watchtower
8654         };
8655         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8656         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8657         // transaction lock time requirements here.
8658         chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize((CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS) as usize, (header, 0));
8659         watchtower_alice.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8660
8661         // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8662         {
8663                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8664                 assert_eq!(txn.len(), 2);
8665                 txn.clear();
8666         }
8667
8668         // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8669         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8670         let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8671         let persister = test_utils::TestPersister::new();
8672         let watchtower_bob = {
8673                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8674                 let mut w = test_utils::TestVecWriter(Vec::new());
8675                 monitor.write(&mut w).unwrap();
8676                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8677                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8678                 assert!(new_monitor == *monitor);
8679                 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);
8680                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8681                 watchtower
8682         };
8683         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8684         watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8685
8686         // Route another payment to generate another update with still previous HTLC pending
8687         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8688         {
8689                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8690         }
8691         check_added_monitors!(nodes[1], 1);
8692
8693         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8694         assert_eq!(updates.update_add_htlcs.len(), 1);
8695         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8696         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8697                 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8698                         // Watchtower Alice should already have seen the block and reject the update
8699                         if let Err(_) =  watchtower_alice.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8700                         if let Ok(_) = watchtower_bob.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8701                         if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8702                 } else { assert!(false); }
8703         } else { assert!(false); };
8704         // Our local monitor is in-sync and hasn't processed yet timeout
8705         check_added_monitors!(nodes[0], 1);
8706
8707         //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8708         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8709         watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8710
8711         // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8712         let bob_state_y;
8713         {
8714                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8715                 assert_eq!(txn.len(), 2);
8716                 bob_state_y = txn[0].clone();
8717                 txn.clear();
8718         };
8719
8720         // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8721         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8722         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);
8723         {
8724                 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8725                 // We broadcast twice the transaction, once due to the HTLC-timeout, once due
8726                 // the onchain detection of the HTLC output
8727                 assert_eq!(htlc_txn.len(), 2);
8728                 check_spends!(htlc_txn[0], bob_state_y);
8729                 check_spends!(htlc_txn[1], bob_state_y);
8730         }
8731 }
8732
8733 #[test]
8734 fn test_pre_lockin_no_chan_closed_update() {
8735         // Test that if a peer closes a channel in response to a funding_created message we don't
8736         // generate a channel update (as the channel cannot appear on chain without a funding_signed
8737         // message).
8738         //
8739         // Doing so would imply a channel monitor update before the initial channel monitor
8740         // registration, violating our API guarantees.
8741         //
8742         // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8743         // then opening a second channel with the same funding output as the first (which is not
8744         // rejected because the first channel does not exist in the ChannelManager) and closing it
8745         // before receiving funding_signed.
8746         let chanmon_cfgs = create_chanmon_cfgs(2);
8747         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8748         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8749         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8750
8751         // Create an initial channel
8752         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8753         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8754         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8755         let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8756         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8757
8758         // Move the first channel through the funding flow...
8759         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], 100000, 42);
8760
8761         nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
8762         check_added_monitors!(nodes[0], 0);
8763
8764         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8765         let channel_id = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8766         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8767         assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8768         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "Hi".to_string() }, true);
8769 }
8770
8771 #[test]
8772 fn test_htlc_no_detection() {
8773         // This test is a mutation to underscore the detection logic bug we had
8774         // before #653. HTLC value routed is above the remaining balance, thus
8775         // inverting HTLC and `to_remote` output. HTLC will come second and
8776         // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8777         // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8778         // outputs order detection for correct spending children filtring.
8779
8780         let chanmon_cfgs = create_chanmon_cfgs(2);
8781         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8782         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8783         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8784
8785         // Create some initial channels
8786         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8787
8788         send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8789         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8790         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8791         assert_eq!(local_txn[0].input.len(), 1);
8792         assert_eq!(local_txn[0].output.len(), 3);
8793         check_spends!(local_txn[0], chan_1.3);
8794
8795         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8796         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8797         connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] });
8798         // We deliberately connect the local tx twice as this should provoke a failure calling
8799         // this test before #653 fix.
8800         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);
8801         check_closed_broadcast!(nodes[0], true);
8802         check_added_monitors!(nodes[0], 1);
8803         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8804         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1);
8805
8806         let htlc_timeout = {
8807                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8808                 assert_eq!(node_txn[1].input.len(), 1);
8809                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8810                 check_spends!(node_txn[1], local_txn[0]);
8811                 node_txn[1].clone()
8812         };
8813
8814         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8815         connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] });
8816         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8817         expect_payment_failed!(nodes[0], our_payment_hash, true);
8818 }
8819
8820 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8821         // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8822         // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8823         // Carol, Alice would be the upstream node, and Carol the downstream.)
8824         //
8825         // Steps of the test:
8826         // 1) Alice sends a HTLC to Carol through Bob.
8827         // 2) Carol doesn't settle the HTLC.
8828         // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8829         // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8830         // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8831         //    but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8832         // 5) Carol release the preimage to Bob off-chain.
8833         // 6) Bob claims the offered output on the broadcasted commitment.
8834         let chanmon_cfgs = create_chanmon_cfgs(3);
8835         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8836         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8837         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8838
8839         // Create some initial channels
8840         let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8841         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8842
8843         // Steps (1) and (2):
8844         // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8845         let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3_000_000);
8846
8847         // Check that Alice's commitment transaction now contains an output for this HTLC.
8848         let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8849         check_spends!(alice_txn[0], chan_ab.3);
8850         assert_eq!(alice_txn[0].output.len(), 2);
8851         check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8852         assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8853         assert_eq!(alice_txn.len(), 2);
8854
8855         // Steps (3) and (4):
8856         // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8857         // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8858         let mut force_closing_node = 0; // Alice force-closes
8859         if !broadcast_alice { force_closing_node = 1; } // Bob force-closes
8860         nodes[force_closing_node].node.force_close_channel(&chan_ab.2).unwrap();
8861         check_closed_broadcast!(nodes[force_closing_node], true);
8862         check_added_monitors!(nodes[force_closing_node], 1);
8863         check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
8864         if go_onchain_before_fulfill {
8865                 let txn_to_broadcast = match broadcast_alice {
8866                         true => alice_txn.clone(),
8867                         false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8868                 };
8869                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8870                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8871                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8872                 if broadcast_alice {
8873                         check_closed_broadcast!(nodes[1], true);
8874                         check_added_monitors!(nodes[1], 1);
8875                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8876                 }
8877                 assert_eq!(bob_txn.len(), 1);
8878                 check_spends!(bob_txn[0], chan_ab.3);
8879         }
8880
8881         // Step (5):
8882         // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8883         // process of removing the HTLC from their commitment transactions.
8884         assert!(nodes[2].node.claim_funds(payment_preimage));
8885         check_added_monitors!(nodes[2], 1);
8886         let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8887         assert!(carol_updates.update_add_htlcs.is_empty());
8888         assert!(carol_updates.update_fail_htlcs.is_empty());
8889         assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8890         assert!(carol_updates.update_fee.is_none());
8891         assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8892
8893         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8894         expect_payment_forwarded!(nodes[1], nodes[0], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false);
8895         // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8896         if !go_onchain_before_fulfill && broadcast_alice {
8897                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8898                 assert_eq!(events.len(), 1);
8899                 match events[0] {
8900                         MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8901                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8902                         },
8903                         _ => panic!("Unexpected event"),
8904                 };
8905         }
8906         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8907         // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8908         // Carol<->Bob's updated commitment transaction info.
8909         check_added_monitors!(nodes[1], 2);
8910
8911         let events = nodes[1].node.get_and_clear_pending_msg_events();
8912         assert_eq!(events.len(), 2);
8913         let bob_revocation = match events[0] {
8914                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8915                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8916                         (*msg).clone()
8917                 },
8918                 _ => panic!("Unexpected event"),
8919         };
8920         let bob_updates = match events[1] {
8921                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8922                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8923                         (*updates).clone()
8924                 },
8925                 _ => panic!("Unexpected event"),
8926         };
8927
8928         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8929         check_added_monitors!(nodes[2], 1);
8930         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8931         check_added_monitors!(nodes[2], 1);
8932
8933         let events = nodes[2].node.get_and_clear_pending_msg_events();
8934         assert_eq!(events.len(), 1);
8935         let carol_revocation = match events[0] {
8936                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8937                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8938                         (*msg).clone()
8939                 },
8940                 _ => panic!("Unexpected event"),
8941         };
8942         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8943         check_added_monitors!(nodes[1], 1);
8944
8945         // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8946         // here's where we put said channel's commitment tx on-chain.
8947         let mut txn_to_broadcast = alice_txn.clone();
8948         if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8949         if !go_onchain_before_fulfill {
8950                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8951                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8952                 // If Bob was the one to force-close, he will have already passed these checks earlier.
8953                 if broadcast_alice {
8954                         check_closed_broadcast!(nodes[1], true);
8955                         check_added_monitors!(nodes[1], 1);
8956                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8957                 }
8958                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8959                 if broadcast_alice {
8960                         // In `connect_block()`, the ChainMonitor and ChannelManager are separately notified about a
8961                         // new block being connected. The ChannelManager being notified triggers a monitor update,
8962                         // which triggers broadcasting our commitment tx and an HTLC-claiming tx. The ChainMonitor
8963                         // being notified triggers the HTLC-claiming tx redundantly, resulting in 3 total txs being
8964                         // broadcasted.
8965                         assert_eq!(bob_txn.len(), 3);
8966                         check_spends!(bob_txn[1], chan_ab.3);
8967                 } else {
8968                         assert_eq!(bob_txn.len(), 2);
8969                         check_spends!(bob_txn[0], chan_ab.3);
8970                 }
8971         }
8972
8973         // Step (6):
8974         // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8975         // broadcasted commitment transaction.
8976         {
8977                 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8978                 if go_onchain_before_fulfill {
8979                         // Bob should now have an extra broadcasted tx, for the preimage-claiming transaction.
8980                         assert_eq!(bob_txn.len(), 2);
8981                 }
8982                 let script_weight = match broadcast_alice {
8983                         true => OFFERED_HTLC_SCRIPT_WEIGHT,
8984                         false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8985                 };
8986                 // If Alice force-closed and Bob didn't receive her commitment transaction until after he
8987                 // received Carol's fulfill, he broadcasts the HTLC-output-claiming transaction first. Else if
8988                 // Bob force closed or if he found out about Alice's commitment tx before receiving Carol's
8989                 // fulfill, then he broadcasts the HTLC-output-claiming transaction second.
8990                 if broadcast_alice && !go_onchain_before_fulfill {
8991                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
8992                         assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8993                 } else {
8994                         check_spends!(bob_txn[1], txn_to_broadcast[0]);
8995                         assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8996                 }
8997         }
8998 }
8999
9000 #[test]
9001 fn test_onchain_htlc_settlement_after_close() {
9002         do_test_onchain_htlc_settlement_after_close(true, true);
9003         do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
9004         do_test_onchain_htlc_settlement_after_close(true, false);
9005         do_test_onchain_htlc_settlement_after_close(false, false);
9006 }
9007
9008 #[test]
9009 fn test_duplicate_chan_id() {
9010         // Test that if a given peer tries to open a channel with the same channel_id as one that is
9011         // already open we reject it and keep the old channel.
9012         //
9013         // Previously, full_stack_target managed to figure out that if you tried to open two channels
9014         // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
9015         // the existing channel when we detect the duplicate new channel, screwing up our monitor
9016         // updating logic for the existing channel.
9017         let chanmon_cfgs = create_chanmon_cfgs(2);
9018         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9019         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9020         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9021
9022         // Create an initial channel
9023         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9024         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9025         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9026         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()));
9027
9028         // Try to create a second channel with the same temporary_channel_id as the first and check
9029         // that it is rejected.
9030         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9031         {
9032                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9033                 assert_eq!(events.len(), 1);
9034                 match events[0] {
9035                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9036                                 // Technically, at this point, nodes[1] would be justified in thinking both the
9037                                 // first (valid) and second (invalid) channels are closed, given they both have
9038                                 // the same non-temporary channel_id. However, currently we do not, so we just
9039                                 // move forward with it.
9040                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9041                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9042                         },
9043                         _ => panic!("Unexpected event"),
9044                 }
9045         }
9046
9047         // Move the first channel through the funding flow...
9048         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
9049
9050         nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
9051         check_added_monitors!(nodes[0], 0);
9052
9053         let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9054         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
9055         {
9056                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
9057                 assert_eq!(added_monitors.len(), 1);
9058                 assert_eq!(added_monitors[0].0, funding_output);
9059                 added_monitors.clear();
9060         }
9061         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9062
9063         let funding_outpoint = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
9064         let channel_id = funding_outpoint.to_channel_id();
9065
9066         // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
9067         // temporary one).
9068
9069         // First try to open a second channel with a temporary channel id equal to the txid-based one.
9070         // Technically this is allowed by the spec, but we don't support it and there's little reason
9071         // to. Still, it shouldn't cause any other issues.
9072         open_chan_msg.temporary_channel_id = channel_id;
9073         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9074         {
9075                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9076                 assert_eq!(events.len(), 1);
9077                 match events[0] {
9078                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9079                                 // Technically, at this point, nodes[1] would be justified in thinking both
9080                                 // channels are closed, but currently we do not, so we just move forward with it.
9081                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9082                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9083                         },
9084                         _ => panic!("Unexpected event"),
9085                 }
9086         }
9087
9088         // Now try to create a second channel which has a duplicate funding output.
9089         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9090         let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9091         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_2_msg);
9092         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()));
9093         create_funding_transaction(&nodes[0], 100000, 42); // Get and check the FundingGenerationReady event
9094
9095         let funding_created = {
9096                 let mut a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
9097                 let mut as_chan = a_channel_lock.by_id.get_mut(&open_chan_2_msg.temporary_channel_id).unwrap();
9098                 let logger = test_utils::TestLogger::new();
9099                 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
9100         };
9101         check_added_monitors!(nodes[0], 0);
9102         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
9103         // At this point we'll try to add a duplicate channel monitor, which will be rejected, but
9104         // still needs to be cleared here.
9105         check_added_monitors!(nodes[1], 1);
9106
9107         // ...still, nodes[1] will reject the duplicate channel.
9108         {
9109                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9110                 assert_eq!(events.len(), 1);
9111                 match events[0] {
9112                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9113                                 // Technically, at this point, nodes[1] would be justified in thinking both
9114                                 // channels are closed, but currently we do not, so we just move forward with it.
9115                                 assert_eq!(msg.channel_id, channel_id);
9116                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9117                         },
9118                         _ => panic!("Unexpected event"),
9119                 }
9120         }
9121
9122         // finally, finish creating the original channel and send a payment over it to make sure
9123         // everything is functional.
9124         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
9125         {
9126                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9127                 assert_eq!(added_monitors.len(), 1);
9128                 assert_eq!(added_monitors[0].0, funding_output);
9129                 added_monitors.clear();
9130         }
9131
9132         let events_4 = nodes[0].node.get_and_clear_pending_events();
9133         assert_eq!(events_4.len(), 0);
9134         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9135         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
9136
9137         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9138         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
9139         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9140         send_payment(&nodes[0], &[&nodes[1]], 8000000);
9141 }
9142
9143 #[test]
9144 fn test_error_chans_closed() {
9145         // Test that we properly handle error messages, closing appropriate channels.
9146         //
9147         // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
9148         // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
9149         // we can test various edge cases around it to ensure we don't regress.
9150         let chanmon_cfgs = create_chanmon_cfgs(3);
9151         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9152         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9153         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9154
9155         // Create some initial channels
9156         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9157         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9158         let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9159
9160         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9161         assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
9162         assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
9163
9164         // Closing a channel from a different peer has no effect
9165         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
9166         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9167
9168         // Closing one channel doesn't impact others
9169         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
9170         check_added_monitors!(nodes[0], 1);
9171         check_closed_broadcast!(nodes[0], false);
9172         check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
9173         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
9174         assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
9175         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);
9176         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);
9177
9178         // A null channel ID should close all channels
9179         let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9180         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
9181         check_added_monitors!(nodes[0], 2);
9182         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
9183         let events = nodes[0].node.get_and_clear_pending_msg_events();
9184         assert_eq!(events.len(), 2);
9185         match events[0] {
9186                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9187                         assert_eq!(msg.contents.flags & 2, 2);
9188                 },
9189                 _ => panic!("Unexpected event"),
9190         }
9191         match events[1] {
9192                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9193                         assert_eq!(msg.contents.flags & 2, 2);
9194                 },
9195                 _ => panic!("Unexpected event"),
9196         }
9197         // Note that at this point users of a standard PeerHandler will end up calling
9198         // peer_disconnected with no_connection_possible set to false, duplicating the
9199         // close-all-channels logic. That's OK, we don't want to end up not force-closing channels for
9200         // users with their own peer handling logic. We duplicate the call here, however.
9201         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9202         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9203
9204         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
9205         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9206         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9207 }
9208
9209 #[test]
9210 fn test_invalid_funding_tx() {
9211         // Test that we properly handle invalid funding transactions sent to us from a peer.
9212         //
9213         // Previously, all other major lightning implementations had failed to properly sanitize
9214         // funding transactions from their counterparties, leading to a multi-implementation critical
9215         // security vulnerability (though we always sanitized properly, we've previously had
9216         // un-released crashes in the sanitization process).
9217         let chanmon_cfgs = create_chanmon_cfgs(2);
9218         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9219         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9220         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9221
9222         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
9223         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()));
9224         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()));
9225
9226         let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], 100_000, 42);
9227         for output in tx.output.iter_mut() {
9228                 // Make the confirmed funding transaction have a bogus script_pubkey
9229                 output.script_pubkey = bitcoin::Script::new();
9230         }
9231
9232         nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, tx.clone(), 0).unwrap();
9233         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()));
9234         check_added_monitors!(nodes[1], 1);
9235
9236         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()));
9237         check_added_monitors!(nodes[0], 1);
9238
9239         let events_1 = nodes[0].node.get_and_clear_pending_events();
9240         assert_eq!(events_1.len(), 0);
9241
9242         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9243         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9244         nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9245
9246         let expected_err = "funding tx had wrong script/value or output index";
9247         confirm_transaction_at(&nodes[1], &tx, 1);
9248         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
9249         check_added_monitors!(nodes[1], 1);
9250         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9251         assert_eq!(events_2.len(), 1);
9252         if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9253                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9254                 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
9255                         assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
9256                 } else { panic!(); }
9257         } else { panic!(); }
9258         assert_eq!(nodes[1].node.list_channels().len(), 0);
9259 }
9260
9261 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9262         // In the first version of the chain::Confirm interface, after a refactor was made to not
9263         // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9264         // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9265         // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9266         // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9267         // spending transaction until height N+1 (or greater). This was due to the way
9268         // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9269         // spending transaction at the height the input transaction was confirmed at, not whether we
9270         // should broadcast a spending transaction at the current height.
9271         // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9272         // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9273         // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9274         // until we learned about an additional block.
9275         //
9276         // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9277         // aren't broadcasting transactions too early (ie not broadcasting them at all).
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 mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9282         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9283
9284         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
9285         let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
9286         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9287         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
9288         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9289
9290         nodes[1].node.force_close_channel(&channel_id).unwrap();
9291         check_closed_broadcast!(nodes[1], true);
9292         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
9293         check_added_monitors!(nodes[1], 1);
9294         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9295         assert_eq!(node_txn.len(), 1);
9296
9297         let conf_height = nodes[1].best_block_info().1;
9298         if !test_height_before_timelock {
9299                 connect_blocks(&nodes[1], 24 * 6);
9300         }
9301         nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9302                 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9303         if test_height_before_timelock {
9304                 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9305                 // generate any events or broadcast any transactions
9306                 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9307                 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9308         } else {
9309                 // We should broadcast an HTLC transaction spending our funding transaction first
9310                 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9311                 assert_eq!(spending_txn.len(), 2);
9312                 assert_eq!(spending_txn[0], node_txn[0]);
9313                 check_spends!(spending_txn[1], node_txn[0]);
9314                 // We should also generate a SpendableOutputs event with the to_self output (as its
9315                 // timelock is up).
9316                 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9317                 assert_eq!(descriptor_spend_txn.len(), 1);
9318
9319                 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9320                 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9321                 // additional block built on top of the current chain.
9322                 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9323                         &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9324                 expect_pending_htlcs_forwardable!(nodes[1]);
9325                 check_added_monitors!(nodes[1], 1);
9326
9327                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9328                 assert!(updates.update_add_htlcs.is_empty());
9329                 assert!(updates.update_fulfill_htlcs.is_empty());
9330                 assert_eq!(updates.update_fail_htlcs.len(), 1);
9331                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9332                 assert!(updates.update_fee.is_none());
9333                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9334                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9335                 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9336         }
9337 }
9338
9339 #[test]
9340 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9341         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9342         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9343 }
9344
9345 #[test]
9346 fn test_forwardable_regen() {
9347         // Tests that if we reload a ChannelManager while forwards are pending we will regenerate the
9348         // PendingHTLCsForwardable event automatically, ensuring we don't forget to forward/receive
9349         // HTLCs.
9350         // We test it for both payment receipt and payment forwarding.
9351
9352         let chanmon_cfgs = create_chanmon_cfgs(3);
9353         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9354         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9355         let persister: test_utils::TestPersister;
9356         let new_chain_monitor: test_utils::TestChainMonitor;
9357         let nodes_1_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
9358         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9359         let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
9360         let chan_id_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known()).2;
9361
9362         // First send a payment to nodes[1]
9363         let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
9364         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
9365         check_added_monitors!(nodes[0], 1);
9366
9367         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9368         assert_eq!(events.len(), 1);
9369         let payment_event = SendEvent::from_event(events.pop().unwrap());
9370         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9371         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9372
9373         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9374
9375         // Next send a payment which is forwarded by nodes[1]
9376         let (route_2, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 200_000);
9377         nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
9378         check_added_monitors!(nodes[0], 1);
9379
9380         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9381         assert_eq!(events.len(), 1);
9382         let payment_event = SendEvent::from_event(events.pop().unwrap());
9383         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9384         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9385
9386         // There is already a PendingHTLCsForwardable event "pending" so another one will not be
9387         // generated
9388         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
9389
9390         // Now restart nodes[1] and make sure it regenerates a single PendingHTLCsForwardable
9391         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9392         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9393
9394         let nodes_1_serialized = nodes[1].node.encode();
9395         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9396         let mut chan_1_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9397         get_monitor!(nodes[1], chan_id_1).write(&mut chan_0_monitor_serialized).unwrap();
9398         get_monitor!(nodes[1], chan_id_2).write(&mut chan_1_monitor_serialized).unwrap();
9399
9400         persister = test_utils::TestPersister::new();
9401         let keys_manager = &chanmon_cfgs[1].keys_manager;
9402         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);
9403         nodes[1].chain_monitor = &new_chain_monitor;
9404
9405         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
9406         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9407                 &mut chan_0_monitor_read, keys_manager).unwrap();
9408         assert!(chan_0_monitor_read.is_empty());
9409         let mut chan_1_monitor_read = &chan_1_monitor_serialized.0[..];
9410         let (_, mut chan_1_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9411                 &mut chan_1_monitor_read, keys_manager).unwrap();
9412         assert!(chan_1_monitor_read.is_empty());
9413
9414         let mut nodes_1_read = &nodes_1_serialized[..];
9415         let (_, nodes_1_deserialized_tmp) = {
9416                 let mut channel_monitors = HashMap::new();
9417                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
9418                 channel_monitors.insert(chan_1_monitor.get_funding_txo().0, &mut chan_1_monitor);
9419                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_1_read, ChannelManagerReadArgs {
9420                         default_config: UserConfig::default(),
9421                         keys_manager,
9422                         fee_estimator: node_cfgs[1].fee_estimator,
9423                         chain_monitor: nodes[1].chain_monitor,
9424                         tx_broadcaster: nodes[1].tx_broadcaster.clone(),
9425                         logger: nodes[1].logger,
9426                         channel_monitors,
9427                 }).unwrap()
9428         };
9429         nodes_1_deserialized = nodes_1_deserialized_tmp;
9430         assert!(nodes_1_read.is_empty());
9431
9432         assert!(nodes[1].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
9433         assert!(nodes[1].chain_monitor.watch_channel(chan_1_monitor.get_funding_txo().0, chan_1_monitor).is_ok());
9434         nodes[1].node = &nodes_1_deserialized;
9435         check_added_monitors!(nodes[1], 2);
9436
9437         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9438         // Note that nodes[1] and nodes[2] resend their funding_locked here since they haven't updated
9439         // the commitment state.
9440         reconnect_nodes(&nodes[1], &nodes[2], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9441
9442         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
9443
9444         expect_pending_htlcs_forwardable!(nodes[1]);
9445         expect_payment_received!(nodes[1], payment_hash, payment_secret, 100_000);
9446         check_added_monitors!(nodes[1], 1);
9447
9448         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9449         assert_eq!(events.len(), 1);
9450         let payment_event = SendEvent::from_event(events.pop().unwrap());
9451         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9452         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false);
9453         expect_pending_htlcs_forwardable!(nodes[2]);
9454         expect_payment_received!(nodes[2], payment_hash_2, payment_secret_2, 200_000);
9455
9456         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
9457         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage_2);
9458 }
9459
9460 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
9461         let chanmon_cfgs = create_chanmon_cfgs(2);
9462         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9463         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9464         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9465
9466         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9467
9468         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
9469                 .with_features(InvoiceFeatures::known());
9470         let route = get_route!(nodes[0], payment_params, 10_000, TEST_FINAL_CLTV).unwrap();
9471
9472         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9473
9474         {
9475                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
9476                 check_added_monitors!(nodes[0], 1);
9477                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9478                 assert_eq!(events.len(), 1);
9479                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9480                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9481                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9482         }
9483         expect_pending_htlcs_forwardable!(nodes[1]);
9484         expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9485
9486         {
9487                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
9488                 check_added_monitors!(nodes[0], 1);
9489                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9490                 assert_eq!(events.len(), 1);
9491                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9492                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9493                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9494                 // At this point, nodes[1] would notice it has too much value for the payment. It will
9495                 // assume the second is a privacy attack (no longer particularly relevant
9496                 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9497                 // the first HTLC delivered above.
9498         }
9499
9500         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9501         nodes[1].node.process_pending_htlc_forwards();
9502
9503         if test_for_second_fail_panic {
9504                 // Now we go fail back the first HTLC from the user end.
9505                 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9506
9507                 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9508                 nodes[1].node.process_pending_htlc_forwards();
9509
9510                 check_added_monitors!(nodes[1], 1);
9511                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9512                 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9513
9514                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9515                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9516                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9517
9518                 let failure_events = nodes[0].node.get_and_clear_pending_events();
9519                 assert_eq!(failure_events.len(), 2);
9520                 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9521                 if let Event::PaymentPathFailed { .. } = failure_events[1] {} else { panic!(); }
9522         } else {
9523                 // Let the second HTLC fail and claim the first
9524                 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9525                 nodes[1].node.process_pending_htlc_forwards();
9526
9527                 check_added_monitors!(nodes[1], 1);
9528                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9529                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9530                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9531
9532                 expect_payment_failed_conditions!(nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9533
9534                 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9535         }
9536 }
9537
9538 #[test]
9539 fn test_dup_htlc_second_fail_panic() {
9540         // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9541         // value for the payment, we'd fail back both HTLCs after generating a `PaymentReceived` event.
9542         // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9543         // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9544         do_test_dup_htlc_second_rejected(true);
9545 }
9546
9547 #[test]
9548 fn test_dup_htlc_second_rejected() {
9549         // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9550         // simply reject the second HTLC but are still able to claim the first HTLC.
9551         do_test_dup_htlc_second_rejected(false);
9552 }
9553
9554 #[test]
9555 fn test_inconsistent_mpp_params() {
9556         // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9557         // such HTLC and allow the second to stay.
9558         let chanmon_cfgs = create_chanmon_cfgs(4);
9559         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9560         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9561         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9562
9563         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9564         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9565         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9566         create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9567
9568         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id())
9569                 .with_features(InvoiceFeatures::known());
9570         let mut route = get_route!(nodes[0], payment_params, 15_000_000, TEST_FINAL_CLTV).unwrap();
9571         assert_eq!(route.paths.len(), 2);
9572         route.paths.sort_by(|path_a, _| {
9573                 // Sort the path so that the path through nodes[1] comes first
9574                 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
9575                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9576         });
9577         let payment_params_opt = Some(payment_params);
9578
9579         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9580
9581         let cur_height = nodes[0].best_block_info().1;
9582         let payment_id = PaymentId([42; 32]);
9583         {
9584                 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();
9585                 check_added_monitors!(nodes[0], 1);
9586
9587                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9588                 assert_eq!(events.len(), 1);
9589                 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9590         }
9591         assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9592
9593         {
9594                 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();
9595                 check_added_monitors!(nodes[0], 1);
9596
9597                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9598                 assert_eq!(events.len(), 1);
9599                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9600
9601                 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9602                 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9603
9604                 expect_pending_htlcs_forwardable!(nodes[2]);
9605                 check_added_monitors!(nodes[2], 1);
9606
9607                 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9608                 assert_eq!(events.len(), 1);
9609                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9610
9611                 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9612                 check_added_monitors!(nodes[3], 0);
9613                 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9614
9615                 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9616                 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9617                 // post-payment_secrets) and fail back the new HTLC.
9618         }
9619         expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9620         nodes[3].node.process_pending_htlc_forwards();
9621         expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9622         nodes[3].node.process_pending_htlc_forwards();
9623
9624         check_added_monitors!(nodes[3], 1);
9625
9626         let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9627         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9628         commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9629
9630         expect_pending_htlcs_forwardable!(nodes[2]);
9631         check_added_monitors!(nodes[2], 1);
9632
9633         let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9634         nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9635         commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9636
9637         expect_payment_failed_conditions!(nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9638
9639         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();
9640         check_added_monitors!(nodes[0], 1);
9641
9642         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9643         assert_eq!(events.len(), 1);
9644         pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9645
9646         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9647 }
9648
9649 #[test]
9650 fn test_keysend_payments_to_public_node() {
9651         let chanmon_cfgs = create_chanmon_cfgs(2);
9652         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9653         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9654         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9655
9656         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9657         let network_graph = nodes[0].network_graph;
9658         let payer_pubkey = nodes[0].node.get_our_node_id();
9659         let payee_pubkey = nodes[1].node.get_our_node_id();
9660         let route_params = RouteParameters {
9661                 payment_params: PaymentParameters::for_keysend(payee_pubkey),
9662                 final_value_msat: 10000,
9663                 final_cltv_expiry_delta: 40,
9664         };
9665         let scorer = test_utils::TestScorer::with_penalty(0);
9666         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9667         let route = find_route(&payer_pubkey, &route_params, network_graph, None, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
9668
9669         let test_preimage = PaymentPreimage([42; 32]);
9670         let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9671         check_added_monitors!(nodes[0], 1);
9672         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9673         assert_eq!(events.len(), 1);
9674         let event = events.pop().unwrap();
9675         let path = vec![&nodes[1]];
9676         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9677         claim_payment(&nodes[0], &path, test_preimage);
9678 }
9679
9680 #[test]
9681 fn test_keysend_payments_to_private_node() {
9682         let chanmon_cfgs = create_chanmon_cfgs(2);
9683         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9684         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9685         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9686
9687         let payer_pubkey = nodes[0].node.get_our_node_id();
9688         let payee_pubkey = nodes[1].node.get_our_node_id();
9689         nodes[0].node.peer_connected(&payee_pubkey, &msgs::Init { features: InitFeatures::known(), remote_network_address: None });
9690         nodes[1].node.peer_connected(&payer_pubkey, &msgs::Init { features: InitFeatures::known(), remote_network_address: None });
9691
9692         let _chan = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
9693         let route_params = RouteParameters {
9694                 payment_params: PaymentParameters::for_keysend(payee_pubkey),
9695                 final_value_msat: 10000,
9696                 final_cltv_expiry_delta: 40,
9697         };
9698         let network_graph = nodes[0].network_graph;
9699         let first_hops = nodes[0].node.list_usable_channels();
9700         let scorer = test_utils::TestScorer::with_penalty(0);
9701         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9702         let route = find_route(
9703                 &payer_pubkey, &route_params, network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
9704                 nodes[0].logger, &scorer, &random_seed_bytes
9705         ).unwrap();
9706
9707         let test_preimage = PaymentPreimage([42; 32]);
9708         let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9709         check_added_monitors!(nodes[0], 1);
9710         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9711         assert_eq!(events.len(), 1);
9712         let event = events.pop().unwrap();
9713         let path = vec![&nodes[1]];
9714         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9715         claim_payment(&nodes[0], &path, test_preimage);
9716 }
9717
9718 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
9719 #[derive(Clone, Copy, PartialEq)]
9720 enum ExposureEvent {
9721         /// Breach occurs at HTLC forwarding (see `send_htlc`)
9722         AtHTLCForward,
9723         /// Breach occurs at HTLC reception (see `update_add_htlc`)
9724         AtHTLCReception,
9725         /// Breach occurs at outbound update_fee (see `send_update_fee`)
9726         AtUpdateFeeOutbound,
9727 }
9728
9729 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool) {
9730         // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
9731         // policy.
9732         //
9733         // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
9734         // trimmed-to-dust HTLC outbound balance and this new payment as included on next
9735         // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
9736         // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
9737         // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
9738         // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
9739         // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
9740         // might be available again for HTLC processing once the dust bandwidth has cleared up.
9741
9742         let chanmon_cfgs = create_chanmon_cfgs(2);
9743         let mut config = test_default_channel_config();
9744         config.channel_options.max_dust_htlc_exposure_msat = 5_000_000; // default setting value
9745         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9746         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
9747         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9748
9749         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
9750         let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9751         open_channel.max_htlc_value_in_flight_msat = 50_000_000;
9752         open_channel.max_accepted_htlcs = 60;
9753         if on_holder_tx {
9754                 open_channel.dust_limit_satoshis = 546;
9755         }
9756         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
9757         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9758         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
9759
9760         let opt_anchors = false;
9761
9762         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], 1_000_000, 42);
9763
9764         if on_holder_tx {
9765                 if let Some(mut chan) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&temporary_channel_id) {
9766                         chan.holder_dust_limit_satoshis = 546;
9767                 }
9768         }
9769
9770         nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
9771         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()));
9772         check_added_monitors!(nodes[1], 1);
9773
9774         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()));
9775         check_added_monitors!(nodes[0], 1);
9776
9777         let (funding_locked, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9778         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
9779         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9780
9781         let dust_buffer_feerate = {
9782                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
9783                 let chan = chan_lock.by_id.get(&channel_id).unwrap();
9784                 chan.get_dust_buffer_feerate(None) as u64
9785         };
9786         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;
9787         let dust_outbound_htlc_on_holder_tx: u64 = config.channel_options.max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
9788
9789         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;
9790         let dust_inbound_htlc_on_holder_tx: u64 = config.channel_options.max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
9791
9792         let dust_htlc_on_counterparty_tx: u64 = 25;
9793         let dust_htlc_on_counterparty_tx_msat: u64 = config.channel_options.max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
9794
9795         if on_holder_tx {
9796                 if dust_outbound_balance {
9797                         // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9798                         // Outbound dust balance: 4372 sats
9799                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
9800                         for i in 0..dust_outbound_htlc_on_holder_tx {
9801                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
9802                                 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at dust HTLC {}", i); }
9803                         }
9804                 } else {
9805                         // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9806                         // Inbound dust balance: 4372 sats
9807                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
9808                         for _ in 0..dust_inbound_htlc_on_holder_tx {
9809                                 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
9810                         }
9811                 }
9812         } else {
9813                 if dust_outbound_balance {
9814                         // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9815                         // Outbound dust balance: 5000 sats
9816                         for i in 0..dust_htlc_on_counterparty_tx {
9817                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
9818                                 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at dust HTLC {}", i); }
9819                         }
9820                 } else {
9821                         // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9822                         // Inbound dust balance: 5000 sats
9823                         for _ in 0..dust_htlc_on_counterparty_tx {
9824                                 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
9825                         }
9826                 }
9827         }
9828
9829         let dust_overflow = dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx + 1);
9830         if exposure_breach_event == ExposureEvent::AtHTLCForward {
9831                 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 });
9832                 let mut config = UserConfig::default();
9833                 // With default dust exposure: 5000 sats
9834                 if on_holder_tx {
9835                         let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * (dust_outbound_htlc_on_holder_tx + 1);
9836                         let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * dust_inbound_htlc_on_holder_tx + dust_outbound_htlc_on_holder_tx_msat;
9837                         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)));
9838                 } else {
9839                         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)));
9840                 }
9841         } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
9842                 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 });
9843                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
9844                 check_added_monitors!(nodes[1], 1);
9845                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9846                 assert_eq!(events.len(), 1);
9847                 let payment_event = SendEvent::from_event(events.remove(0));
9848                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9849                 // With default dust exposure: 5000 sats
9850                 if on_holder_tx {
9851                         // Outbound dust balance: 6399 sats
9852                         let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
9853                         let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
9854                         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);
9855                 } else {
9856                         // Outbound dust balance: 5200 sats
9857                         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);
9858                 }
9859         } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
9860                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 2_500_000);
9861                 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at update_fee-swallowed HTLC", ); }
9862                 {
9863                         let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9864                         *feerate_lock = *feerate_lock * 10;
9865                 }
9866                 nodes[0].node.timer_tick_occurred();
9867                 check_added_monitors!(nodes[0], 1);
9868                 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);
9869         }
9870
9871         let _ = nodes[0].node.get_and_clear_pending_msg_events();
9872         let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9873         added_monitors.clear();
9874 }
9875
9876 #[test]
9877 fn test_max_dust_htlc_exposure() {
9878         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true);
9879         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true);
9880         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true);
9881         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false);
9882         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false);
9883         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false);
9884         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true);
9885         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false);
9886         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true);
9887         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false);
9888         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false);
9889         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true);
9890 }