Stop relying on the `*Features::known` method in functional tests
[rust-lightning] / lightning / src / ln / functional_tests.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
8 // licenses.
9
10 //! Tests that test standing up a network of ChannelManagers, creating channels, sending
11 //! payments/messages between them, and often checking the resulting ChannelMonitors are able to
12 //! claim outputs on-chain.
13
14 use chain;
15 use chain::{Confirm, Listen, Watch};
16 use chain::chaininterface::LowerBoundedFeeEstimator;
17 use chain::channelmonitor;
18 use chain::channelmonitor::{ChannelMonitor, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY};
19 use chain::transaction::OutPoint;
20 use chain::keysinterface::{BaseSign, KeysInterface};
21 use ln::{PaymentPreimage, PaymentSecret, PaymentHash};
22 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};
23 use ln::channelmanager::{self, ChannelManager, ChannelManagerReadArgs, PaymentId, RAACommitmentOrder, PaymentSendFailure, BREAKDOWN_TIMEOUT, MIN_CLTV_EXPIRY_DELTA, PAYMENT_EXPIRY_BLOCKS};
24 use ln::channel::{Channel, ChannelError};
25 use ln::{chan_utils, onion_utils};
26 use ln::chan_utils::{OFFERED_HTLC_SCRIPT_WEIGHT, htlc_success_tx_weight, htlc_timeout_tx_weight, HTLCOutputInCommitment};
27 use routing::gossip::{NetworkGraph, NetworkUpdate};
28 use routing::router::{PaymentParameters, Route, RouteHop, RouteParameters, find_route, get_route};
29 use ln::features::{ChannelFeatures, NodeFeatures};
30 use ln::msgs;
31 use ln::msgs::{ChannelMessageHandler, RoutingMessageHandler, ErrorAction};
32 use util::enforcing_trait_impls::EnforcingSigner;
33 use util::{byte_utils, test_utils};
34 use util::events::{Event, MessageSendEvent, MessageSendEventsProvider, PaymentPurpose, ClosureReason, HTLCDestination};
35 use util::errors::APIError;
36 use util::ser::{Writeable, ReadableArgs};
37 use util::config::UserConfig;
38
39 use bitcoin::hash_types::BlockHash;
40 use bitcoin::blockdata::block::{Block, BlockHeader};
41 use bitcoin::blockdata::script::{Builder, Script};
42 use bitcoin::blockdata::opcodes;
43 use bitcoin::blockdata::constants::genesis_block;
44 use bitcoin::network::constants::Network;
45 use bitcoin::{PackedLockTime, Sequence, Transaction, TxIn, TxMerkleNode, TxOut, Witness};
46 use bitcoin::OutPoint as BitcoinOutPoint;
47
48 use bitcoin::secp256k1::Secp256k1;
49 use bitcoin::secp256k1::{PublicKey,SecretKey};
50
51 use regex;
52
53 use io;
54 use prelude::*;
55 use alloc::collections::BTreeSet;
56 use core::default::Default;
57 use core::iter::repeat;
58 use bitcoin::hashes::Hash;
59 use sync::{Arc, Mutex};
60
61 use ln::functional_test_utils::*;
62 use ln::chan_utils::CommitmentTransaction;
63
64 #[test]
65 fn test_insane_channel_opens() {
66         // Stand up a network of 2 nodes
67         use ln::channel::TOTAL_BITCOIN_SUPPLY_SATOSHIS;
68         let mut cfg = UserConfig::default();
69         cfg.channel_handshake_limits.max_funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1;
70         let chanmon_cfgs = create_chanmon_cfgs(2);
71         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
72         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(cfg)]);
73         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
74
75         // Instantiate channel parameters where we push the maximum msats given our
76         // funding satoshis
77         let channel_value_sat = 31337; // same as funding satoshis
78         let channel_reserve_satoshis = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value_sat, &cfg);
79         let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
80
81         // Have node0 initiate a channel to node1 with aforementioned parameters
82         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
83
84         // Extract the channel open message from node0 to node1
85         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
86
87         // Test helper that asserts we get the correct error string given a mutator
88         // that supposedly makes the channel open message insane
89         let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
90                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &message_mutator(open_channel_message.clone()));
91                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
92                 assert_eq!(msg_events.len(), 1);
93                 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
94                 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
95                         match action {
96                                 &ErrorAction::SendErrorMessage { .. } => {
97                                         nodes[1].logger.assert_log_regex("lightning::ln::channelmanager".to_string(), expected_regex, 1);
98                                 },
99                                 _ => panic!("unexpected event!"),
100                         }
101                 } else { assert!(false); }
102         };
103
104         use ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
105
106         // Test all mutations that would make the channel open message insane
107         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 });
108         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 });
109
110         insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
111
112         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 });
113
114         insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
115
116         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 });
117
118         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 });
119
120         insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
121
122         insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
123 }
124
125 #[test]
126 fn test_funding_exceeds_no_wumbo_limit() {
127         // Test that if a peer does not support wumbo channels, we'll refuse to open a wumbo channel to
128         // them.
129         use ln::channel::MAX_FUNDING_SATOSHIS_NO_WUMBO;
130         let chanmon_cfgs = create_chanmon_cfgs(2);
131         let mut node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
132         node_cfgs[1].features = channelmanager::provided_init_features().clear_wumbo();
133         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
134         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
135
136         match nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), MAX_FUNDING_SATOSHIS_NO_WUMBO + 1, 0, 42, None) {
137                 Err(APIError::APIMisuseError { err }) => {
138                         assert_eq!(format!("funding_value must not exceed {}, it was {}", MAX_FUNDING_SATOSHIS_NO_WUMBO, MAX_FUNDING_SATOSHIS_NO_WUMBO + 1), err);
139                 },
140                 _ => panic!()
141         }
142 }
143
144 fn do_test_counterparty_no_reserve(send_from_initiator: bool) {
145         // A peer providing a channel_reserve_satoshis of 0 (or less than our dust limit) is insecure,
146         // but only for them. Because some LSPs do it with some level of trust of the clients (for a
147         // substantial UX improvement), we explicitly allow it. Because it's unlikely to happen often
148         // in normal testing, we test it explicitly here.
149         let chanmon_cfgs = create_chanmon_cfgs(2);
150         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
151         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
152         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
153         let default_config = UserConfig::default();
154
155         // Have node0 initiate a channel to node1 with aforementioned parameters
156         let mut push_amt = 100_000_000;
157         let feerate_per_kw = 253;
158         let opt_anchors = false;
159         push_amt -= feerate_per_kw as u64 * (commitment_tx_base_weight(opt_anchors) + 4 * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000 * 1000;
160         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
161
162         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();
163         let mut open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
164         if !send_from_initiator {
165                 open_channel_message.channel_reserve_satoshis = 0;
166                 open_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
167         }
168         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_channel_message);
169
170         // Extract the channel accept message from node1 to node0
171         let mut accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
172         if send_from_initiator {
173                 accept_channel_message.channel_reserve_satoshis = 0;
174                 accept_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
175         }
176         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_channel_message);
177         {
178                 let mut lock;
179                 let mut chan = get_channel_ref!(if send_from_initiator { &nodes[1] } else { &nodes[0] }, lock, temp_channel_id);
180                 chan.holder_selected_channel_reserve_satoshis = 0;
181                 chan.holder_max_htlc_value_in_flight_msat = 100_000_000;
182         }
183
184         let funding_tx = sign_funding_transaction(&nodes[0], &nodes[1], 100_000, temp_channel_id);
185         let funding_msgs = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &funding_tx);
186         create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_msgs.0);
187
188         // nodes[0] should now be able to send the full balance to nodes[1], violating nodes[1]'s
189         // security model if it ever tries to send funds back to nodes[0] (but that's not our problem).
190         if send_from_initiator {
191                 send_payment(&nodes[0], &[&nodes[1]], 100_000_000
192                         // Note that for outbound channels we have to consider the commitment tx fee and the
193                         // "fee spike buffer", which is currently a multiple of the total commitment tx fee as
194                         // well as an additional HTLC.
195                         - FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE * commit_tx_fee_msat(feerate_per_kw, 2, opt_anchors));
196         } else {
197                 send_payment(&nodes[1], &[&nodes[0]], push_amt);
198         }
199 }
200
201 #[test]
202 fn test_counterparty_no_reserve() {
203         do_test_counterparty_no_reserve(true);
204         do_test_counterparty_no_reserve(false);
205 }
206
207 #[test]
208 fn test_async_inbound_update_fee() {
209         let chanmon_cfgs = create_chanmon_cfgs(2);
210         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
211         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
212         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
213         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
214
215         // balancing
216         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
217
218         // A                                        B
219         // update_fee                            ->
220         // send (1) commitment_signed            -.
221         //                                       <- update_add_htlc/commitment_signed
222         // send (2) RAA (awaiting remote revoke) -.
223         // (1) commitment_signed is delivered    ->
224         //                                       .- send (3) RAA (awaiting remote revoke)
225         // (2) RAA is delivered                  ->
226         //                                       .- send (4) commitment_signed
227         //                                       <- (3) RAA is delivered
228         // send (5) commitment_signed            -.
229         //                                       <- (4) commitment_signed is delivered
230         // send (6) RAA                          -.
231         // (5) commitment_signed is delivered    ->
232         //                                       <- RAA
233         // (6) RAA is delivered                  ->
234
235         // First nodes[0] generates an update_fee
236         {
237                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
238                 *feerate_lock += 20;
239         }
240         nodes[0].node.timer_tick_occurred();
241         check_added_monitors!(nodes[0], 1);
242
243         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
244         assert_eq!(events_0.len(), 1);
245         let (update_msg, commitment_signed) = match events_0[0] { // (1)
246                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
247                         (update_fee.as_ref(), commitment_signed)
248                 },
249                 _ => panic!("Unexpected event"),
250         };
251
252         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
253
254         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
255         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
256         nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
257         check_added_monitors!(nodes[1], 1);
258
259         let payment_event = {
260                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
261                 assert_eq!(events_1.len(), 1);
262                 SendEvent::from_event(events_1.remove(0))
263         };
264         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
265         assert_eq!(payment_event.msgs.len(), 1);
266
267         // ...now when the messages get delivered everyone should be happy
268         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
269         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
270         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
271         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
272         check_added_monitors!(nodes[0], 1);
273
274         // deliver(1), generate (3):
275         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
276         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
277         // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
278         check_added_monitors!(nodes[1], 1);
279
280         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
281         let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
282         assert!(bs_update.update_add_htlcs.is_empty()); // (4)
283         assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
284         assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
285         assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
286         assert!(bs_update.update_fee.is_none()); // (4)
287         check_added_monitors!(nodes[1], 1);
288
289         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
290         let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
291         assert!(as_update.update_add_htlcs.is_empty()); // (5)
292         assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
293         assert!(as_update.update_fail_htlcs.is_empty()); // (5)
294         assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
295         assert!(as_update.update_fee.is_none()); // (5)
296         check_added_monitors!(nodes[0], 1);
297
298         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
299         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
300         // only (6) so get_event_msg's assert(len == 1) passes
301         check_added_monitors!(nodes[0], 1);
302
303         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
304         let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
305         check_added_monitors!(nodes[1], 1);
306
307         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
308         check_added_monitors!(nodes[0], 1);
309
310         let events_2 = nodes[0].node.get_and_clear_pending_events();
311         assert_eq!(events_2.len(), 1);
312         match events_2[0] {
313                 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
314                 _ => panic!("Unexpected event"),
315         }
316
317         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
318         check_added_monitors!(nodes[1], 1);
319 }
320
321 #[test]
322 fn test_update_fee_unordered_raa() {
323         // Just the intro to the previous test followed by an out-of-order RAA (which caused a
324         // crash in an earlier version of the update_fee patch)
325         let chanmon_cfgs = create_chanmon_cfgs(2);
326         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
327         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
328         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
329         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
330
331         // balancing
332         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
333
334         // First nodes[0] generates an update_fee
335         {
336                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
337                 *feerate_lock += 20;
338         }
339         nodes[0].node.timer_tick_occurred();
340         check_added_monitors!(nodes[0], 1);
341
342         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
343         assert_eq!(events_0.len(), 1);
344         let update_msg = match events_0[0] { // (1)
345                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
346                         update_fee.as_ref()
347                 },
348                 _ => panic!("Unexpected event"),
349         };
350
351         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
352
353         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
354         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
355         nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
356         check_added_monitors!(nodes[1], 1);
357
358         let payment_event = {
359                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
360                 assert_eq!(events_1.len(), 1);
361                 SendEvent::from_event(events_1.remove(0))
362         };
363         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
364         assert_eq!(payment_event.msgs.len(), 1);
365
366         // ...now when the messages get delivered everyone should be happy
367         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
368         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
369         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
370         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
371         check_added_monitors!(nodes[0], 1);
372
373         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
374         check_added_monitors!(nodes[1], 1);
375
376         // We can't continue, sadly, because our (1) now has a bogus signature
377 }
378
379 #[test]
380 fn test_multi_flight_update_fee() {
381         let chanmon_cfgs = create_chanmon_cfgs(2);
382         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
383         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
384         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
385         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
386
387         // A                                        B
388         // update_fee/commitment_signed          ->
389         //                                       .- send (1) RAA and (2) commitment_signed
390         // update_fee (never committed)          ->
391         // (3) update_fee                        ->
392         // We have to manually generate the above update_fee, it is allowed by the protocol but we
393         // don't track which updates correspond to which revoke_and_ack responses so we're in
394         // AwaitingRAA mode and will not generate the update_fee yet.
395         //                                       <- (1) RAA delivered
396         // (3) is generated and send (4) CS      -.
397         // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
398         // know the per_commitment_point to use for it.
399         //                                       <- (2) commitment_signed delivered
400         // revoke_and_ack                        ->
401         //                                          B should send no response here
402         // (4) commitment_signed delivered       ->
403         //                                       <- RAA/commitment_signed delivered
404         // revoke_and_ack                        ->
405
406         // First nodes[0] generates an update_fee
407         let initial_feerate;
408         {
409                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
410                 initial_feerate = *feerate_lock;
411                 *feerate_lock = initial_feerate + 20;
412         }
413         nodes[0].node.timer_tick_occurred();
414         check_added_monitors!(nodes[0], 1);
415
416         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
417         assert_eq!(events_0.len(), 1);
418         let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
419                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
420                         (update_fee.as_ref().unwrap(), commitment_signed)
421                 },
422                 _ => panic!("Unexpected event"),
423         };
424
425         // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
426         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
427         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
428         let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
429         check_added_monitors!(nodes[1], 1);
430
431         // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
432         // transaction:
433         {
434                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
435                 *feerate_lock = initial_feerate + 40;
436         }
437         nodes[0].node.timer_tick_occurred();
438         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
439         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
440
441         // Create the (3) update_fee message that nodes[0] will generate before it does...
442         let mut update_msg_2 = msgs::UpdateFee {
443                 channel_id: update_msg_1.channel_id.clone(),
444                 feerate_per_kw: (initial_feerate + 30) as u32,
445         };
446
447         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
448
449         update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
450         // Deliver (3)
451         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
452
453         // Deliver (1), generating (3) and (4)
454         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
455         let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
456         check_added_monitors!(nodes[0], 1);
457         assert!(as_second_update.update_add_htlcs.is_empty());
458         assert!(as_second_update.update_fulfill_htlcs.is_empty());
459         assert!(as_second_update.update_fail_htlcs.is_empty());
460         assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
461         // Check that the update_fee newly generated matches what we delivered:
462         assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
463         assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
464
465         // Deliver (2) commitment_signed
466         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
467         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
468         check_added_monitors!(nodes[0], 1);
469         // No commitment_signed so get_event_msg's assert(len == 1) passes
470
471         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
472         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
473         check_added_monitors!(nodes[1], 1);
474
475         // Delever (4)
476         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
477         let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
478         check_added_monitors!(nodes[1], 1);
479
480         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
481         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
482         check_added_monitors!(nodes[0], 1);
483
484         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
485         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
486         // No commitment_signed so get_event_msg's assert(len == 1) passes
487         check_added_monitors!(nodes[0], 1);
488
489         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
490         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
491         check_added_monitors!(nodes[1], 1);
492 }
493
494 fn do_test_sanity_on_in_flight_opens(steps: u8) {
495         // Previously, we had issues deserializing channels when we hadn't connected the first block
496         // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
497         // serialization round-trips and simply do steps towards opening a channel and then drop the
498         // Node objects.
499
500         let chanmon_cfgs = create_chanmon_cfgs(2);
501         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
502         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
503         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
504
505         if steps & 0b1000_0000 != 0{
506                 let block = Block {
507                         header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
508                         txdata: vec![],
509                 };
510                 connect_block(&nodes[0], &block);
511                 connect_block(&nodes[1], &block);
512         }
513
514         if steps & 0x0f == 0 { return; }
515         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
516         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
517
518         if steps & 0x0f == 1 { return; }
519         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_channel);
520         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
521
522         if steps & 0x0f == 2 { return; }
523         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_channel);
524
525         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
526
527         if steps & 0x0f == 3 { return; }
528         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
529         check_added_monitors!(nodes[0], 0);
530         let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
531
532         if steps & 0x0f == 4 { return; }
533         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
534         {
535                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
536                 assert_eq!(added_monitors.len(), 1);
537                 assert_eq!(added_monitors[0].0, funding_output);
538                 added_monitors.clear();
539         }
540         let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
541
542         if steps & 0x0f == 5 { return; }
543         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
544         {
545                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
546                 assert_eq!(added_monitors.len(), 1);
547                 assert_eq!(added_monitors[0].0, funding_output);
548                 added_monitors.clear();
549         }
550
551         let events_4 = nodes[0].node.get_and_clear_pending_events();
552         assert_eq!(events_4.len(), 0);
553
554         if steps & 0x0f == 6 { return; }
555         create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
556
557         if steps & 0x0f == 7 { return; }
558         confirm_transaction_at(&nodes[0], &tx, 2);
559         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
560         create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
561 }
562
563 #[test]
564 fn test_sanity_on_in_flight_opens() {
565         do_test_sanity_on_in_flight_opens(0);
566         do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
567         do_test_sanity_on_in_flight_opens(1);
568         do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
569         do_test_sanity_on_in_flight_opens(2);
570         do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
571         do_test_sanity_on_in_flight_opens(3);
572         do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
573         do_test_sanity_on_in_flight_opens(4);
574         do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
575         do_test_sanity_on_in_flight_opens(5);
576         do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
577         do_test_sanity_on_in_flight_opens(6);
578         do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
579         do_test_sanity_on_in_flight_opens(7);
580         do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
581         do_test_sanity_on_in_flight_opens(8);
582         do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
583 }
584
585 #[test]
586 fn test_update_fee_vanilla() {
587         let chanmon_cfgs = create_chanmon_cfgs(2);
588         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
589         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
590         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
591         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
592
593         {
594                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
595                 *feerate_lock += 25;
596         }
597         nodes[0].node.timer_tick_occurred();
598         check_added_monitors!(nodes[0], 1);
599
600         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
601         assert_eq!(events_0.len(), 1);
602         let (update_msg, commitment_signed) = match events_0[0] {
603                         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 } } => {
604                         (update_fee.as_ref(), commitment_signed)
605                 },
606                 _ => panic!("Unexpected event"),
607         };
608         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
609
610         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
611         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
612         check_added_monitors!(nodes[1], 1);
613
614         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
615         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
616         check_added_monitors!(nodes[0], 1);
617
618         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
619         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
620         // No commitment_signed so get_event_msg's assert(len == 1) passes
621         check_added_monitors!(nodes[0], 1);
622
623         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
624         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
625         check_added_monitors!(nodes[1], 1);
626 }
627
628 #[test]
629 fn test_update_fee_that_funder_cannot_afford() {
630         let chanmon_cfgs = create_chanmon_cfgs(2);
631         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
632         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
633         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
634         let channel_value = 5000;
635         let push_sats = 700;
636         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, push_sats * 1000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
637         let channel_id = chan.2;
638         let secp_ctx = Secp256k1::new();
639         let default_config = UserConfig::default();
640         let bs_channel_reserve_sats = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value, &default_config);
641
642         let opt_anchors = false;
643
644         // Calculate the maximum feerate that A can afford. Note that we don't send an update_fee
645         // CONCURRENT_INBOUND_HTLC_FEE_BUFFER HTLCs before actually running out of local balance, so we
646         // calculate two different feerates here - the expected local limit as well as the expected
647         // remote limit.
648         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;
649         let non_buffer_feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / commitment_tx_base_weight(opt_anchors)) as u32;
650         {
651                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
652                 *feerate_lock = feerate;
653         }
654         nodes[0].node.timer_tick_occurred();
655         check_added_monitors!(nodes[0], 1);
656         let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
657
658         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
659
660         commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
661
662         // Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate set above.
663         {
664                 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
665
666                 //We made sure neither party's funds are below the dust limit and there are no HTLCs here
667                 assert_eq!(commitment_tx.output.len(), 2);
668                 let total_fee: u64 = commit_tx_fee_msat(feerate, 0, opt_anchors) / 1000;
669                 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
670                 actual_fee = channel_value - actual_fee;
671                 assert_eq!(total_fee, actual_fee);
672         }
673
674         {
675                 // Increment the feerate by a small constant, accounting for rounding errors
676                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
677                 *feerate_lock += 4;
678         }
679         nodes[0].node.timer_tick_occurred();
680         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot afford to send new feerate at {}", feerate + 4), 1);
681         check_added_monitors!(nodes[0], 0);
682
683         const INITIAL_COMMITMENT_NUMBER: u64 = 281474976710654;
684
685         // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
686         // needed to sign the new commitment tx and (2) sign the new commitment tx.
687         let (local_revocation_basepoint, local_htlc_basepoint, local_funding) = {
688                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
689                 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
690                 let chan_signer = local_chan.get_signer();
691                 let pubkeys = chan_signer.pubkeys();
692                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
693                  pubkeys.funding_pubkey)
694         };
695         let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point, remote_funding) = {
696                 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
697                 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
698                 let chan_signer = remote_chan.get_signer();
699                 let pubkeys = chan_signer.pubkeys();
700                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
701                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
702                  pubkeys.funding_pubkey)
703         };
704
705         // Assemble the set of keys we can use for signatures for our commitment_signed message.
706         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
707                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
708
709         let res = {
710                 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
711                 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
712                 let local_chan_signer = local_chan.get_signer();
713                 let mut htlcs: Vec<(HTLCOutputInCommitment, ())> = vec![];
714                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
715                         INITIAL_COMMITMENT_NUMBER - 1,
716                         push_sats,
717                         channel_value - push_sats - commit_tx_fee_msat(non_buffer_feerate + 4, 0, opt_anchors) / 1000,
718                         opt_anchors, local_funding, remote_funding,
719                         commit_tx_keys.clone(),
720                         non_buffer_feerate + 4,
721                         &mut htlcs,
722                         &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
723                 );
724                 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
725         };
726
727         let commit_signed_msg = msgs::CommitmentSigned {
728                 channel_id: chan.2,
729                 signature: res.0,
730                 htlc_signatures: res.1
731         };
732
733         let update_fee = msgs::UpdateFee {
734                 channel_id: chan.2,
735                 feerate_per_kw: non_buffer_feerate + 4,
736         };
737
738         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_fee);
739
740         //While producing the commitment_signed response after handling a received update_fee request the
741         //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
742         //Should produce and error.
743         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
744         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
745         check_added_monitors!(nodes[1], 1);
746         check_closed_broadcast!(nodes[1], true);
747         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: String::from("Funding remote cannot afford proposed new fee") });
748 }
749
750 #[test]
751 fn test_update_fee_with_fundee_update_add_htlc() {
752         let chanmon_cfgs = create_chanmon_cfgs(2);
753         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
754         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
755         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
756         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
757
758         // balancing
759         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
760
761         {
762                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
763                 *feerate_lock += 20;
764         }
765         nodes[0].node.timer_tick_occurred();
766         check_added_monitors!(nodes[0], 1);
767
768         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
769         assert_eq!(events_0.len(), 1);
770         let (update_msg, commitment_signed) = match events_0[0] {
771                         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 } } => {
772                         (update_fee.as_ref(), commitment_signed)
773                 },
774                 _ => panic!("Unexpected event"),
775         };
776         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
777         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
778         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
779         check_added_monitors!(nodes[1], 1);
780
781         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 800000);
782
783         // nothing happens since node[1] is in AwaitingRemoteRevoke
784         nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
785         {
786                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
787                 assert_eq!(added_monitors.len(), 0);
788                 added_monitors.clear();
789         }
790         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
791         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
792         // node[1] has nothing to do
793
794         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
795         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
796         check_added_monitors!(nodes[0], 1);
797
798         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
799         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
800         // No commitment_signed so get_event_msg's assert(len == 1) passes
801         check_added_monitors!(nodes[0], 1);
802         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
803         check_added_monitors!(nodes[1], 1);
804         // AwaitingRemoteRevoke ends here
805
806         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
807         assert_eq!(commitment_update.update_add_htlcs.len(), 1);
808         assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
809         assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
810         assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
811         assert_eq!(commitment_update.update_fee.is_none(), true);
812
813         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
814         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
815         check_added_monitors!(nodes[0], 1);
816         let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
817
818         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
819         check_added_monitors!(nodes[1], 1);
820         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
821
822         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
823         check_added_monitors!(nodes[1], 1);
824         let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
825         // No commitment_signed so get_event_msg's assert(len == 1) passes
826
827         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
828         check_added_monitors!(nodes[0], 1);
829         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
830
831         expect_pending_htlcs_forwardable!(nodes[0]);
832
833         let events = nodes[0].node.get_and_clear_pending_events();
834         assert_eq!(events.len(), 1);
835         match events[0] {
836                 Event::PaymentReceived { .. } => { },
837                 _ => panic!("Unexpected event"),
838         };
839
840         claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
841
842         send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
843         send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
844         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
845         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
846         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
847 }
848
849 #[test]
850 fn test_update_fee() {
851         let chanmon_cfgs = create_chanmon_cfgs(2);
852         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
853         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
854         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
855         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
856         let channel_id = chan.2;
857
858         // A                                        B
859         // (1) update_fee/commitment_signed      ->
860         //                                       <- (2) revoke_and_ack
861         //                                       .- send (3) commitment_signed
862         // (4) update_fee/commitment_signed      ->
863         //                                       .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
864         //                                       <- (3) commitment_signed delivered
865         // send (6) revoke_and_ack               -.
866         //                                       <- (5) deliver revoke_and_ack
867         // (6) deliver revoke_and_ack            ->
868         //                                       .- send (7) commitment_signed in response to (4)
869         //                                       <- (7) deliver commitment_signed
870         // revoke_and_ack                        ->
871
872         // Create and deliver (1)...
873         let feerate;
874         {
875                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
876                 feerate = *feerate_lock;
877                 *feerate_lock = feerate + 20;
878         }
879         nodes[0].node.timer_tick_occurred();
880         check_added_monitors!(nodes[0], 1);
881
882         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
883         assert_eq!(events_0.len(), 1);
884         let (update_msg, commitment_signed) = match events_0[0] {
885                         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 } } => {
886                         (update_fee.as_ref(), commitment_signed)
887                 },
888                 _ => panic!("Unexpected event"),
889         };
890         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
891
892         // Generate (2) and (3):
893         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
894         let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
895         check_added_monitors!(nodes[1], 1);
896
897         // Deliver (2):
898         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
899         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
900         check_added_monitors!(nodes[0], 1);
901
902         // Create and deliver (4)...
903         {
904                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
905                 *feerate_lock = feerate + 30;
906         }
907         nodes[0].node.timer_tick_occurred();
908         check_added_monitors!(nodes[0], 1);
909         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
910         assert_eq!(events_0.len(), 1);
911         let (update_msg, commitment_signed) = match events_0[0] {
912                         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 } } => {
913                         (update_fee.as_ref(), commitment_signed)
914                 },
915                 _ => panic!("Unexpected event"),
916         };
917
918         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
919         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
920         check_added_monitors!(nodes[1], 1);
921         // ... creating (5)
922         let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
923         // No commitment_signed so get_event_msg's assert(len == 1) passes
924
925         // Handle (3), creating (6):
926         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
927         check_added_monitors!(nodes[0], 1);
928         let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
929         // No commitment_signed so get_event_msg's assert(len == 1) passes
930
931         // Deliver (5):
932         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
933         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
934         check_added_monitors!(nodes[0], 1);
935
936         // Deliver (6), creating (7):
937         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
938         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
939         assert!(commitment_update.update_add_htlcs.is_empty());
940         assert!(commitment_update.update_fulfill_htlcs.is_empty());
941         assert!(commitment_update.update_fail_htlcs.is_empty());
942         assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
943         assert!(commitment_update.update_fee.is_none());
944         check_added_monitors!(nodes[1], 1);
945
946         // Deliver (7)
947         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
948         check_added_monitors!(nodes[0], 1);
949         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
950         // No commitment_signed so get_event_msg's assert(len == 1) passes
951
952         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
953         check_added_monitors!(nodes[1], 1);
954         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
955
956         assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
957         assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
958         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
959         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
960         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
961 }
962
963 #[test]
964 fn fake_network_test() {
965         // Simple test which builds a network of ChannelManagers, connects them to each other, and
966         // tests that payments get routed and transactions broadcast in semi-reasonable ways.
967         let chanmon_cfgs = create_chanmon_cfgs(4);
968         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
969         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
970         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
971
972         // Create some initial channels
973         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
974         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
975         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
976
977         // Rebalance the network a bit by relaying one payment through all the channels...
978         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
979         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
980         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
981         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
982
983         // Send some more payments
984         send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
985         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
986         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
987
988         // Test failure packets
989         let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
990         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
991
992         // Add a new channel that skips 3
993         let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
994
995         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
996         send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
997         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
998         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
999         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1000         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1001         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1002
1003         // Do some rebalance loop payments, simultaneously
1004         let mut hops = Vec::with_capacity(3);
1005         hops.push(RouteHop {
1006                 pubkey: nodes[2].node.get_our_node_id(),
1007                 node_features: NodeFeatures::empty(),
1008                 short_channel_id: chan_2.0.contents.short_channel_id,
1009                 channel_features: ChannelFeatures::empty(),
1010                 fee_msat: 0,
1011                 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1012         });
1013         hops.push(RouteHop {
1014                 pubkey: nodes[3].node.get_our_node_id(),
1015                 node_features: NodeFeatures::empty(),
1016                 short_channel_id: chan_3.0.contents.short_channel_id,
1017                 channel_features: ChannelFeatures::empty(),
1018                 fee_msat: 0,
1019                 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1020         });
1021         hops.push(RouteHop {
1022                 pubkey: nodes[1].node.get_our_node_id(),
1023                 node_features: channelmanager::provided_node_features(),
1024                 short_channel_id: chan_4.0.contents.short_channel_id,
1025                 channel_features: channelmanager::provided_channel_features(),
1026                 fee_msat: 1000000,
1027                 cltv_expiry_delta: TEST_FINAL_CLTV,
1028         });
1029         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;
1030         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;
1031         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;
1032
1033         let mut hops = Vec::with_capacity(3);
1034         hops.push(RouteHop {
1035                 pubkey: nodes[3].node.get_our_node_id(),
1036                 node_features: NodeFeatures::empty(),
1037                 short_channel_id: chan_4.0.contents.short_channel_id,
1038                 channel_features: ChannelFeatures::empty(),
1039                 fee_msat: 0,
1040                 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1041         });
1042         hops.push(RouteHop {
1043                 pubkey: nodes[2].node.get_our_node_id(),
1044                 node_features: NodeFeatures::empty(),
1045                 short_channel_id: chan_3.0.contents.short_channel_id,
1046                 channel_features: ChannelFeatures::empty(),
1047                 fee_msat: 0,
1048                 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1049         });
1050         hops.push(RouteHop {
1051                 pubkey: nodes[1].node.get_our_node_id(),
1052                 node_features: channelmanager::provided_node_features(),
1053                 short_channel_id: chan_2.0.contents.short_channel_id,
1054                 channel_features: channelmanager::provided_channel_features(),
1055                 fee_msat: 1000000,
1056                 cltv_expiry_delta: TEST_FINAL_CLTV,
1057         });
1058         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;
1059         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;
1060         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;
1061
1062         // Claim the rebalances...
1063         fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1064         claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1065
1066         // Close down the channels...
1067         close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1068         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
1069         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1070         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1071         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1072         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1073         close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1074         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1075         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1076         close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1077         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1078         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1079 }
1080
1081 #[test]
1082 fn holding_cell_htlc_counting() {
1083         // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1084         // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1085         // commitment dance rounds.
1086         let chanmon_cfgs = create_chanmon_cfgs(3);
1087         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1088         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1089         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1090         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1091         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1092
1093         let mut payments = Vec::new();
1094         for _ in 0..::ln::channel::OUR_MAX_HTLCS {
1095                 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1096                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
1097                 payments.push((payment_preimage, payment_hash));
1098         }
1099         check_added_monitors!(nodes[1], 1);
1100
1101         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1102         assert_eq!(events.len(), 1);
1103         let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1104         assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1105
1106         // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1107         // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1108         // another HTLC.
1109         let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1110         {
1111                 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)), true, APIError::ChannelUnavailable { ref err },
1112                         assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1113                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1114                 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1115         }
1116
1117         // This should also be true if we try to forward a payment.
1118         let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1119         {
1120                 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
1121                 check_added_monitors!(nodes[0], 1);
1122         }
1123
1124         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1125         assert_eq!(events.len(), 1);
1126         let payment_event = SendEvent::from_event(events.pop().unwrap());
1127         assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1128
1129         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1130         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1131         // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1132         // fails), the second will process the resulting failure and fail the HTLC backward.
1133         expect_pending_htlcs_forwardable!(nodes[1]);
1134         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
1135         check_added_monitors!(nodes[1], 1);
1136
1137         let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1138         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1139         commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1140
1141         expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1142
1143         // Now forward all the pending HTLCs and claim them back
1144         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1145         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1146         check_added_monitors!(nodes[2], 1);
1147
1148         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1149         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1150         check_added_monitors!(nodes[1], 1);
1151         let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1152
1153         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1154         check_added_monitors!(nodes[1], 1);
1155         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1156
1157         for ref update in as_updates.update_add_htlcs.iter() {
1158                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1159         }
1160         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1161         check_added_monitors!(nodes[2], 1);
1162         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1163         check_added_monitors!(nodes[2], 1);
1164         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1165
1166         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1167         check_added_monitors!(nodes[1], 1);
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_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1171
1172         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1173         check_added_monitors!(nodes[2], 1);
1174
1175         expect_pending_htlcs_forwardable!(nodes[2]);
1176
1177         let events = nodes[2].node.get_and_clear_pending_events();
1178         assert_eq!(events.len(), payments.len());
1179         for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1180                 match event {
1181                         &Event::PaymentReceived { ref payment_hash, .. } => {
1182                                 assert_eq!(*payment_hash, *hash);
1183                         },
1184                         _ => panic!("Unexpected event"),
1185                 };
1186         }
1187
1188         for (preimage, _) in payments.drain(..) {
1189                 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1190         }
1191
1192         send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1193 }
1194
1195 #[test]
1196 fn duplicate_htlc_test() {
1197         // Test that we accept duplicate payment_hash HTLCs across the network and that
1198         // claiming/failing them are all separate and don't affect each other
1199         let chanmon_cfgs = create_chanmon_cfgs(6);
1200         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1201         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1202         let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1203
1204         // Create some initial channels to route via 3 to 4/5 from 0/1/2
1205         create_announced_chan_between_nodes(&nodes, 0, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1206         create_announced_chan_between_nodes(&nodes, 1, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1207         create_announced_chan_between_nodes(&nodes, 2, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1208         create_announced_chan_between_nodes(&nodes, 3, 4, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1209         create_announced_chan_between_nodes(&nodes, 3, 5, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1210
1211         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1212
1213         *nodes[0].network_payment_count.borrow_mut() -= 1;
1214         assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1215
1216         *nodes[0].network_payment_count.borrow_mut() -= 1;
1217         assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1218
1219         claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1220         fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1221         claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1222 }
1223
1224 #[test]
1225 fn test_duplicate_htlc_different_direction_onchain() {
1226         // Test that ChannelMonitor doesn't generate 2 preimage txn
1227         // when we have 2 HTLCs with same preimage that go across a node
1228         // in opposite directions, even with the same payment secret.
1229         let chanmon_cfgs = create_chanmon_cfgs(2);
1230         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1231         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1232         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1233
1234         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1235
1236         // balancing
1237         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1238
1239         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1240
1241         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1242         let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200).unwrap();
1243         send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1244
1245         // Provide preimage to node 0 by claiming payment
1246         nodes[0].node.claim_funds(payment_preimage);
1247         expect_payment_claimed!(nodes[0], payment_hash, 800_000);
1248         check_added_monitors!(nodes[0], 1);
1249
1250         // Broadcast node 1 commitment txn
1251         let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1252
1253         assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1254         let mut has_both_htlcs = 0; // check htlcs match ones committed
1255         for outp in remote_txn[0].output.iter() {
1256                 if outp.value == 800_000 / 1000 {
1257                         has_both_htlcs += 1;
1258                 } else if outp.value == 900_000 / 1000 {
1259                         has_both_htlcs += 1;
1260                 }
1261         }
1262         assert_eq!(has_both_htlcs, 2);
1263
1264         mine_transaction(&nodes[0], &remote_txn[0]);
1265         check_added_monitors!(nodes[0], 1);
1266         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
1267         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
1268
1269         let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1270         assert_eq!(claim_txn.len(), 5);
1271
1272         check_spends!(claim_txn[0], remote_txn[0]); // Immediate HTLC claim with preimage
1273         check_spends!(claim_txn[1], chan_1.3); // Alternative commitment tx
1274         check_spends!(claim_txn[2], claim_txn[1]); // HTLC spend in alternative commitment tx
1275
1276         check_spends!(claim_txn[3], remote_txn[0]);
1277         check_spends!(claim_txn[4], remote_txn[0]);
1278         let preimage_tx = &claim_txn[0];
1279         let (preimage_bump_tx, timeout_tx) = if claim_txn[3].input[0].previous_output == preimage_tx.input[0].previous_output {
1280                 (&claim_txn[3], &claim_txn[4])
1281         } else {
1282                 (&claim_txn[4], &claim_txn[3])
1283         };
1284
1285         assert_eq!(preimage_tx.input.len(), 1);
1286         assert_eq!(preimage_bump_tx.input.len(), 1);
1287
1288         assert_eq!(preimage_tx.input.len(), 1);
1289         assert_eq!(preimage_tx.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1290         assert_eq!(remote_txn[0].output[preimage_tx.input[0].previous_output.vout as usize].value, 800);
1291
1292         assert_eq!(timeout_tx.input.len(), 1);
1293         assert_eq!(timeout_tx.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1294         check_spends!(timeout_tx, remote_txn[0]);
1295         assert_eq!(remote_txn[0].output[timeout_tx.input[0].previous_output.vout as usize].value, 900);
1296
1297         let events = nodes[0].node.get_and_clear_pending_msg_events();
1298         assert_eq!(events.len(), 3);
1299         for e in events {
1300                 match e {
1301                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1302                         MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1303                                 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1304                                 assert_eq!(msg.data, "Channel closed because commitment or closing transaction was confirmed on chain.");
1305                         },
1306                         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, .. } } => {
1307                                 assert!(update_add_htlcs.is_empty());
1308                                 assert!(update_fail_htlcs.is_empty());
1309                                 assert_eq!(update_fulfill_htlcs.len(), 1);
1310                                 assert!(update_fail_malformed_htlcs.is_empty());
1311                                 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1312                         },
1313                         _ => panic!("Unexpected event"),
1314                 }
1315         }
1316 }
1317
1318 #[test]
1319 fn test_basic_channel_reserve() {
1320         let chanmon_cfgs = create_chanmon_cfgs(2);
1321         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1322         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1323         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1324         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1325
1326         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1327         let channel_reserve = chan_stat.channel_reserve_msat;
1328
1329         // The 2* and +1 are for the fee spike reserve.
1330         let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], chan.2), 1 + 1, get_opt_anchors!(nodes[0], chan.2));
1331         let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1332         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send + 1);
1333         let err = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).err().unwrap();
1334         match err {
1335                 PaymentSendFailure::AllFailedRetrySafe(ref fails) => {
1336                         match &fails[0] {
1337                                 &APIError::ChannelUnavailable{ref err} =>
1338                                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1339                                 _ => panic!("Unexpected error variant"),
1340                         }
1341                 },
1342                 _ => panic!("Unexpected error variant"),
1343         }
1344         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1345         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);
1346
1347         send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1348 }
1349
1350 #[test]
1351 fn test_fee_spike_violation_fails_htlc() {
1352         let chanmon_cfgs = create_chanmon_cfgs(2);
1353         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1354         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1355         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1356         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1357
1358         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3460001);
1359         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1360         let secp_ctx = Secp256k1::new();
1361         let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1362
1363         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1364
1365         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1366         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &Some(payment_secret), cur_height, &None).unwrap();
1367         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1368         let msg = msgs::UpdateAddHTLC {
1369                 channel_id: chan.2,
1370                 htlc_id: 0,
1371                 amount_msat: htlc_msat,
1372                 payment_hash: payment_hash,
1373                 cltv_expiry: htlc_cltv,
1374                 onion_routing_packet: onion_packet,
1375         };
1376
1377         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1378
1379         // Now manually create the commitment_signed message corresponding to the update_add
1380         // nodes[0] just sent. In the code for construction of this message, "local" refers
1381         // to the sender of the message, and "remote" refers to the receiver.
1382
1383         let feerate_per_kw = get_feerate!(nodes[0], chan.2);
1384
1385         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1386
1387         // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1388         // needed to sign the new commitment tx and (2) sign the new commitment tx.
1389         let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1390                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
1391                 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
1392                 let chan_signer = local_chan.get_signer();
1393                 // Make the signer believe we validated another commitment, so we can release the secret
1394                 chan_signer.get_enforcement_state().last_holder_commitment -= 1;
1395
1396                 let pubkeys = chan_signer.pubkeys();
1397                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1398                  chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1399                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1400                  chan_signer.pubkeys().funding_pubkey)
1401         };
1402         let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1403                 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
1404                 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
1405                 let chan_signer = remote_chan.get_signer();
1406                 let pubkeys = chan_signer.pubkeys();
1407                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1408                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1409                  chan_signer.pubkeys().funding_pubkey)
1410         };
1411
1412         // Assemble the set of keys we can use for signatures for our commitment_signed message.
1413         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1414                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
1415
1416         // Build the remote commitment transaction so we can sign it, and then later use the
1417         // signature for the commitment_signed message.
1418         let local_chan_balance = 1313;
1419
1420         let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1421                 offered: false,
1422                 amount_msat: 3460001,
1423                 cltv_expiry: htlc_cltv,
1424                 payment_hash,
1425                 transaction_output_index: Some(1),
1426         };
1427
1428         let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1429
1430         let res = {
1431                 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
1432                 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
1433                 let local_chan_signer = local_chan.get_signer();
1434                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1435                         commitment_number,
1436                         95000,
1437                         local_chan_balance,
1438                         local_chan.opt_anchors(), local_funding, remote_funding,
1439                         commit_tx_keys.clone(),
1440                         feerate_per_kw,
1441                         &mut vec![(accepted_htlc_info, ())],
1442                         &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1443                 );
1444                 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
1445         };
1446
1447         let commit_signed_msg = msgs::CommitmentSigned {
1448                 channel_id: chan.2,
1449                 signature: res.0,
1450                 htlc_signatures: res.1
1451         };
1452
1453         // Send the commitment_signed message to the nodes[1].
1454         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1455         let _ = nodes[1].node.get_and_clear_pending_msg_events();
1456
1457         // Send the RAA to nodes[1].
1458         let raa_msg = msgs::RevokeAndACK {
1459                 channel_id: chan.2,
1460                 per_commitment_secret: local_secret,
1461                 next_per_commitment_point: next_local_point
1462         };
1463         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1464
1465         let events = nodes[1].node.get_and_clear_pending_msg_events();
1466         assert_eq!(events.len(), 1);
1467         // Make sure the HTLC failed in the way we expect.
1468         match events[0] {
1469                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1470                         assert_eq!(update_fail_htlcs.len(), 1);
1471                         update_fail_htlcs[0].clone()
1472                 },
1473                 _ => panic!("Unexpected event"),
1474         };
1475         nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1476                 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", ::hex::encode(raa_msg.channel_id)), 1);
1477
1478         check_added_monitors!(nodes[1], 2);
1479 }
1480
1481 #[test]
1482 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1483         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1484         // Set the fee rate for the channel very high, to the point where the fundee
1485         // sending any above-dust amount would result in a channel reserve violation.
1486         // In this test we check that we would be prevented from sending an HTLC in
1487         // this situation.
1488         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1489         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1490         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1491         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1492         let default_config = UserConfig::default();
1493         let opt_anchors = false;
1494
1495         let mut push_amt = 100_000_000;
1496         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1497
1498         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1499
1500         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1501
1502         // Sending exactly enough to hit the reserve amount should be accepted
1503         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1504                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1505         }
1506
1507         // However one more HTLC should be significantly over the reserve amount and fail.
1508         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1509         unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1510                 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1511         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1512         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);
1513 }
1514
1515 #[test]
1516 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1517         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1518         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1519         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1520         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1521         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1522         let default_config = UserConfig::default();
1523         let opt_anchors = false;
1524
1525         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1526         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1527         // transaction fee with 0 HTLCs (183 sats)).
1528         let mut push_amt = 100_000_000;
1529         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1530         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1531         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1532
1533         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1534         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1535                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1536         }
1537
1538         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 700_000);
1539         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1540         let secp_ctx = Secp256k1::new();
1541         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1542         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1543         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1544         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 700_000, &Some(payment_secret), cur_height, &None).unwrap();
1545         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1546         let msg = msgs::UpdateAddHTLC {
1547                 channel_id: chan.2,
1548                 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1549                 amount_msat: htlc_msat,
1550                 payment_hash: payment_hash,
1551                 cltv_expiry: htlc_cltv,
1552                 onion_routing_packet: onion_packet,
1553         };
1554
1555         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1556         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1557         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);
1558         assert_eq!(nodes[0].node.list_channels().len(), 0);
1559         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1560         assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1561         check_added_monitors!(nodes[0], 1);
1562         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() });
1563 }
1564
1565 #[test]
1566 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1567         // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1568         // calculating our commitment transaction fee (this was previously broken).
1569         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1570         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1571
1572         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1573         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1574         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1575         let default_config = UserConfig::default();
1576         let opt_anchors = false;
1577
1578         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1579         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1580         // transaction fee with 0 HTLCs (183 sats)).
1581         let mut push_amt = 100_000_000;
1582         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1583         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1584         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1585
1586         let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1587                 + feerate_per_kw as u64 * htlc_success_tx_weight(opt_anchors) / 1000 * 1000 - 1;
1588         // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1589         // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1590         // commitment transaction fee.
1591         let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1592
1593         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1594         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1595                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1596         }
1597
1598         // One more than the dust amt should fail, however.
1599         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt + 1);
1600         unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1601                 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1602 }
1603
1604 #[test]
1605 fn test_chan_init_feerate_unaffordability() {
1606         // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to
1607         // channel reserve and feerate requirements.
1608         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1609         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1610         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1611         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1612         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1613         let default_config = UserConfig::default();
1614         let opt_anchors = false;
1615
1616         // Set the push_msat amount such that nodes[0] will not be able to afford to add even a single
1617         // HTLC.
1618         let mut push_amt = 100_000_000;
1619         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1620         assert_eq!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt + 1, 42, None).unwrap_err(),
1621                 APIError::APIMisuseError { err: "Funding amount (356) can't even pay fee for initial commitment transaction fee of 357.".to_string() });
1622
1623         // During open, we don't have a "counterparty channel reserve" to check against, so that
1624         // requirement only comes into play on the open_channel handling side.
1625         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1626         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt, 42, None).unwrap();
1627         let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
1628         open_channel_msg.push_msat += 1;
1629         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_channel_msg);
1630
1631         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1632         assert_eq!(msg_events.len(), 1);
1633         match msg_events[0] {
1634                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1635                         assert_eq!(msg.data, "Insufficient funding amount for initial reserve");
1636                 },
1637                 _ => panic!("Unexpected event"),
1638         }
1639 }
1640
1641 #[test]
1642 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1643         // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1644         // calculating our counterparty's commitment transaction fee (this was previously broken).
1645         let chanmon_cfgs = create_chanmon_cfgs(2);
1646         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1647         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1648         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1649         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1650
1651         let payment_amt = 46000; // Dust amount
1652         // In the previous code, these first four payments would succeed.
1653         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1654         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1655         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1656         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1657
1658         // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1659         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
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         // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1666         // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1667         // transaction fee and therefore perceived this next payment as a channel reserve violation.
1668         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1669 }
1670
1671 #[test]
1672 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1673         let chanmon_cfgs = create_chanmon_cfgs(3);
1674         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1675         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1676         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1677         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1678         let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1679
1680         let feemsat = 239;
1681         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1682         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1683         let feerate = get_feerate!(nodes[0], chan.2);
1684         let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
1685
1686         // Add a 2* and +1 for the fee spike reserve.
1687         let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1688         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;
1689         let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1690
1691         // Add a pending HTLC.
1692         let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1693         let payment_event_1 = {
1694                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1695                 check_added_monitors!(nodes[0], 1);
1696
1697                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1698                 assert_eq!(events.len(), 1);
1699                 SendEvent::from_event(events.remove(0))
1700         };
1701         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1702
1703         // Attempt to trigger a channel reserve violation --> payment failure.
1704         let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2, opt_anchors);
1705         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;
1706         let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1707         let (route_2, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_2);
1708
1709         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1710         let secp_ctx = Secp256k1::new();
1711         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1712         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1713         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1714         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height, &None).unwrap();
1715         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1716         let msg = msgs::UpdateAddHTLC {
1717                 channel_id: chan.2,
1718                 htlc_id: 1,
1719                 amount_msat: htlc_msat + 1,
1720                 payment_hash: our_payment_hash_1,
1721                 cltv_expiry: htlc_cltv,
1722                 onion_routing_packet: onion_packet,
1723         };
1724
1725         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1726         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1727         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1728         assert_eq!(nodes[1].node.list_channels().len(), 1);
1729         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1730         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1731         check_added_monitors!(nodes[1], 1);
1732         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() });
1733 }
1734
1735 #[test]
1736 fn test_inbound_outbound_capacity_is_not_zero() {
1737         let chanmon_cfgs = create_chanmon_cfgs(2);
1738         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1739         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1740         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1741         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1742         let channels0 = node_chanmgrs[0].list_channels();
1743         let channels1 = node_chanmgrs[1].list_channels();
1744         let default_config = UserConfig::default();
1745         assert_eq!(channels0.len(), 1);
1746         assert_eq!(channels1.len(), 1);
1747
1748         let reserve = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config);
1749         assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1750         assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1751
1752         assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1753         assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1754 }
1755
1756 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64, opt_anchors: bool) -> u64 {
1757         (commitment_tx_base_weight(opt_anchors) + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1758 }
1759
1760 #[test]
1761 fn test_channel_reserve_holding_cell_htlcs() {
1762         let chanmon_cfgs = create_chanmon_cfgs(3);
1763         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1764         // When this test was written, the default base fee floated based on the HTLC count.
1765         // It is now fixed, so we simply set the fee to the expected value here.
1766         let mut config = test_default_channel_config();
1767         config.channel_config.forwarding_fee_base_msat = 239;
1768         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1769         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1770         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1771         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1772
1773         let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1774         let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1775
1776         let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1777         let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1778
1779         macro_rules! expect_forward {
1780                 ($node: expr) => {{
1781                         let mut events = $node.node.get_and_clear_pending_msg_events();
1782                         assert_eq!(events.len(), 1);
1783                         check_added_monitors!($node, 1);
1784                         let payment_event = SendEvent::from_event(events.remove(0));
1785                         payment_event
1786                 }}
1787         }
1788
1789         let feemsat = 239; // set above
1790         let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1791         let feerate = get_feerate!(nodes[0], chan_1.2);
1792         let opt_anchors = get_opt_anchors!(nodes[0], chan_1.2);
1793
1794         let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1795
1796         // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1797         {
1798                 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id())
1799                         .with_features(channelmanager::provided_invoice_features()).with_max_channel_saturation_power_of_half(0);
1800                 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], payment_params, recv_value_0, TEST_FINAL_CLTV);
1801                 route.paths[0].last_mut().unwrap().fee_msat += 1;
1802                 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1803
1804                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1805                         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)));
1806                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1807                 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);
1808         }
1809
1810         // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1811         // nodes[0]'s wealth
1812         loop {
1813                 let amt_msat = recv_value_0 + total_fee_msat;
1814                 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1815                 // Also, ensure that each payment has enough to be over the dust limit to
1816                 // ensure it'll be included in each commit tx fee calculation.
1817                 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1818                 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1819                 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1820                         break;
1821                 }
1822
1823                 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id())
1824                         .with_features(channelmanager::provided_invoice_features()).with_max_channel_saturation_power_of_half(0);
1825                 let route = get_route!(nodes[0], payment_params, recv_value_0, TEST_FINAL_CLTV).unwrap();
1826                 let (payment_preimage, ..) = send_along_route(&nodes[0], route, &[&nodes[1], &nodes[2]], recv_value_0);
1827                 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1828
1829                 let (stat01_, stat11_, stat12_, stat22_) = (
1830                         get_channel_value_stat!(nodes[0], chan_1.2),
1831                         get_channel_value_stat!(nodes[1], chan_1.2),
1832                         get_channel_value_stat!(nodes[1], chan_2.2),
1833                         get_channel_value_stat!(nodes[2], chan_2.2),
1834                 );
1835
1836                 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1837                 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1838                 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1839                 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1840                 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1841         }
1842
1843         // adding pending output.
1844         // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1845         // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1846         // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1847         // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1848         // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1849         // cases where 1 msat over X amount will cause a payment failure, but anything less than
1850         // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1851         // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1852         // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1853         // policy.
1854         let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1855         let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1856         let amt_msat_1 = recv_value_1 + total_fee_msat;
1857
1858         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);
1859         let payment_event_1 = {
1860                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1861                 check_added_monitors!(nodes[0], 1);
1862
1863                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1864                 assert_eq!(events.len(), 1);
1865                 SendEvent::from_event(events.remove(0))
1866         };
1867         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1868
1869         // channel reserve test with htlc pending output > 0
1870         let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1871         {
1872                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_2 + 1);
1873                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1874                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1875                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1876         }
1877
1878         // split the rest to test holding cell
1879         let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1880         let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1881         let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1882         let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1883         {
1884                 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
1885                 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);
1886         }
1887
1888         // now see if they go through on both sides
1889         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);
1890         // but this will stuck in the holding cell
1891         nodes[0].node.send_payment(&route_21, our_payment_hash_21, &Some(our_payment_secret_21)).unwrap();
1892         check_added_monitors!(nodes[0], 0);
1893         let events = nodes[0].node.get_and_clear_pending_events();
1894         assert_eq!(events.len(), 0);
1895
1896         // test with outbound holding cell amount > 0
1897         {
1898                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22+1);
1899                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1900                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1901                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1902                 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);
1903         }
1904
1905         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);
1906         // this will also stuck in the holding cell
1907         nodes[0].node.send_payment(&route_22, our_payment_hash_22, &Some(our_payment_secret_22)).unwrap();
1908         check_added_monitors!(nodes[0], 0);
1909         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1910         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1911
1912         // flush the pending htlc
1913         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1914         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1915         check_added_monitors!(nodes[1], 1);
1916
1917         // the pending htlc should be promoted to committed
1918         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1919         check_added_monitors!(nodes[0], 1);
1920         let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1921
1922         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1923         let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1924         // No commitment_signed so get_event_msg's assert(len == 1) passes
1925         check_added_monitors!(nodes[0], 1);
1926
1927         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1928         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1929         check_added_monitors!(nodes[1], 1);
1930
1931         expect_pending_htlcs_forwardable!(nodes[1]);
1932
1933         let ref payment_event_11 = expect_forward!(nodes[1]);
1934         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1935         commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1936
1937         expect_pending_htlcs_forwardable!(nodes[2]);
1938         expect_payment_received!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
1939
1940         // flush the htlcs in the holding cell
1941         assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1942         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1943         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1944         commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1945         expect_pending_htlcs_forwardable!(nodes[1]);
1946
1947         let ref payment_event_3 = expect_forward!(nodes[1]);
1948         assert_eq!(payment_event_3.msgs.len(), 2);
1949         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1950         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1951
1952         commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1953         expect_pending_htlcs_forwardable!(nodes[2]);
1954
1955         let events = nodes[2].node.get_and_clear_pending_events();
1956         assert_eq!(events.len(), 2);
1957         match events[0] {
1958                 Event::PaymentReceived { ref payment_hash, ref purpose, amount_msat } => {
1959                         assert_eq!(our_payment_hash_21, *payment_hash);
1960                         assert_eq!(recv_value_21, amount_msat);
1961                         match &purpose {
1962                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1963                                         assert!(payment_preimage.is_none());
1964                                         assert_eq!(our_payment_secret_21, *payment_secret);
1965                                 },
1966                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
1967                         }
1968                 },
1969                 _ => panic!("Unexpected event"),
1970         }
1971         match events[1] {
1972                 Event::PaymentReceived { ref payment_hash, ref purpose, amount_msat } => {
1973                         assert_eq!(our_payment_hash_22, *payment_hash);
1974                         assert_eq!(recv_value_22, amount_msat);
1975                         match &purpose {
1976                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1977                                         assert!(payment_preimage.is_none());
1978                                         assert_eq!(our_payment_secret_22, *payment_secret);
1979                                 },
1980                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
1981                         }
1982                 },
1983                 _ => panic!("Unexpected event"),
1984         }
1985
1986         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
1987         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
1988         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
1989
1990         let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1, opt_anchors);
1991         let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
1992         send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
1993
1994         let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
1995         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);
1996         let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
1997         assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
1998         assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
1999
2000         let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
2001         assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2002 }
2003
2004 #[test]
2005 fn channel_reserve_in_flight_removes() {
2006         // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2007         // can send to its counterparty, but due to update ordering, the other side may not yet have
2008         // considered those HTLCs fully removed.
2009         // This tests that we don't count HTLCs which will not be included in the next remote
2010         // commitment transaction towards the reserve value (as it implies no commitment transaction
2011         // will be generated which violates the remote reserve value).
2012         // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2013         // To test this we:
2014         //  * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2015         //    you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2016         //    you only consider the value of the first HTLC, it may not),
2017         //  * start routing a third HTLC from A to B,
2018         //  * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2019         //    the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2020         //  * deliver the first fulfill from B
2021         //  * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2022         //    claim,
2023         //  * deliver A's response CS and RAA.
2024         //    This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2025         //    removed it fully. B now has the push_msat plus the first two HTLCs in value.
2026         //  * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2027         //    of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2028         let chanmon_cfgs = create_chanmon_cfgs(2);
2029         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2030         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2031         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2032         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2033
2034         let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
2035         // Route the first two HTLCs.
2036         let payment_value_1 = b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000;
2037         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], payment_value_1);
2038         let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20_000);
2039
2040         // Start routing the third HTLC (this is just used to get everyone in the right state).
2041         let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
2042         let send_1 = {
2043                 nodes[0].node.send_payment(&route, payment_hash_3, &Some(payment_secret_3)).unwrap();
2044                 check_added_monitors!(nodes[0], 1);
2045                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2046                 assert_eq!(events.len(), 1);
2047                 SendEvent::from_event(events.remove(0))
2048         };
2049
2050         // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2051         // initial fulfill/CS.
2052         nodes[1].node.claim_funds(payment_preimage_1);
2053         expect_payment_claimed!(nodes[1], payment_hash_1, payment_value_1);
2054         check_added_monitors!(nodes[1], 1);
2055         let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2056
2057         // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2058         // remove the second HTLC when we send the HTLC back from B to A.
2059         nodes[1].node.claim_funds(payment_preimage_2);
2060         expect_payment_claimed!(nodes[1], payment_hash_2, 20_000);
2061         check_added_monitors!(nodes[1], 1);
2062         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2063
2064         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2065         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2066         check_added_monitors!(nodes[0], 1);
2067         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2068         expect_payment_sent_without_paths!(nodes[0], payment_preimage_1);
2069
2070         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2071         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2072         check_added_monitors!(nodes[1], 1);
2073         // B is already AwaitingRAA, so cant generate a CS here
2074         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2075
2076         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2077         check_added_monitors!(nodes[1], 1);
2078         let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2079
2080         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2081         check_added_monitors!(nodes[0], 1);
2082         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2083
2084         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2085         check_added_monitors!(nodes[1], 1);
2086         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2087
2088         // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2089         // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2090         // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2091         // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2092         // on-chain as necessary).
2093         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2094         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2095         check_added_monitors!(nodes[0], 1);
2096         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2097         expect_payment_sent_without_paths!(nodes[0], payment_preimage_2);
2098
2099         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2100         check_added_monitors!(nodes[1], 1);
2101         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2102
2103         expect_pending_htlcs_forwardable!(nodes[1]);
2104         expect_payment_received!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2105
2106         // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2107         // resolve the second HTLC from A's point of view.
2108         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2109         check_added_monitors!(nodes[0], 1);
2110         expect_payment_path_successful!(nodes[0]);
2111         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2112
2113         // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2114         // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2115         let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2116         let send_2 = {
2117                 nodes[1].node.send_payment(&route, payment_hash_4, &Some(payment_secret_4)).unwrap();
2118                 check_added_monitors!(nodes[1], 1);
2119                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2120                 assert_eq!(events.len(), 1);
2121                 SendEvent::from_event(events.remove(0))
2122         };
2123
2124         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2125         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2126         check_added_monitors!(nodes[0], 1);
2127         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2128
2129         // Now just resolve all the outstanding messages/HTLCs for completeness...
2130
2131         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2132         check_added_monitors!(nodes[1], 1);
2133         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2134
2135         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2136         check_added_monitors!(nodes[1], 1);
2137
2138         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2139         check_added_monitors!(nodes[0], 1);
2140         expect_payment_path_successful!(nodes[0]);
2141         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2142
2143         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2144         check_added_monitors!(nodes[1], 1);
2145         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2146
2147         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2148         check_added_monitors!(nodes[0], 1);
2149
2150         expect_pending_htlcs_forwardable!(nodes[0]);
2151         expect_payment_received!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2152
2153         claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2154         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2155 }
2156
2157 #[test]
2158 fn channel_monitor_network_test() {
2159         // Simple test which builds a network of ChannelManagers, connects them to each other, and
2160         // tests that ChannelMonitor is able to recover from various states.
2161         let chanmon_cfgs = create_chanmon_cfgs(5);
2162         let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2163         let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2164         let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2165
2166         // Create some initial channels
2167         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2168         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2169         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2170         let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2171
2172         // Make sure all nodes are at the same starting height
2173         connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2174         connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2175         connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2176         connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2177         connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2178
2179         // Rebalance the network a bit by relaying one payment through all the channels...
2180         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2181         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2182         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2183         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2184
2185         // Simple case with no pending HTLCs:
2186         nodes[1].node.force_close_broadcasting_latest_txn(&chan_1.2, &nodes[0].node.get_our_node_id()).unwrap();
2187         check_added_monitors!(nodes[1], 1);
2188         check_closed_broadcast!(nodes[1], true);
2189         {
2190                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2191                 assert_eq!(node_txn.len(), 1);
2192                 mine_transaction(&nodes[0], &node_txn[0]);
2193                 check_added_monitors!(nodes[0], 1);
2194                 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
2195         }
2196         check_closed_broadcast!(nodes[0], true);
2197         assert_eq!(nodes[0].node.list_channels().len(), 0);
2198         assert_eq!(nodes[1].node.list_channels().len(), 1);
2199         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2200         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2201
2202         // One pending HTLC is discarded by the force-close:
2203         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[1], &[&nodes[2], &nodes[3]], 3_000_000);
2204
2205         // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2206         // broadcasted until we reach the timelock time).
2207         nodes[1].node.force_close_broadcasting_latest_txn(&chan_2.2, &nodes[2].node.get_our_node_id()).unwrap();
2208         check_closed_broadcast!(nodes[1], true);
2209         check_added_monitors!(nodes[1], 1);
2210         {
2211                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2212                 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2213                 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2214                 mine_transaction(&nodes[2], &node_txn[0]);
2215                 check_added_monitors!(nodes[2], 1);
2216                 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
2217         }
2218         check_closed_broadcast!(nodes[2], true);
2219         assert_eq!(nodes[1].node.list_channels().len(), 0);
2220         assert_eq!(nodes[2].node.list_channels().len(), 1);
2221         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2222         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2223
2224         macro_rules! claim_funds {
2225                 ($node: expr, $prev_node: expr, $preimage: expr, $payment_hash: expr) => {
2226                         {
2227                                 $node.node.claim_funds($preimage);
2228                                 expect_payment_claimed!($node, $payment_hash, 3_000_000);
2229                                 check_added_monitors!($node, 1);
2230
2231                                 let events = $node.node.get_and_clear_pending_msg_events();
2232                                 assert_eq!(events.len(), 1);
2233                                 match events[0] {
2234                                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2235                                                 assert!(update_add_htlcs.is_empty());
2236                                                 assert!(update_fail_htlcs.is_empty());
2237                                                 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2238                                         },
2239                                         _ => panic!("Unexpected event"),
2240                                 };
2241                         }
2242                 }
2243         }
2244
2245         // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2246         // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2247         nodes[2].node.force_close_broadcasting_latest_txn(&chan_3.2, &nodes[3].node.get_our_node_id()).unwrap();
2248         check_added_monitors!(nodes[2], 1);
2249         check_closed_broadcast!(nodes[2], true);
2250         let node2_commitment_txid;
2251         {
2252                 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2253                 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2254                 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2255                 node2_commitment_txid = node_txn[0].txid();
2256
2257                 // Claim the payment on nodes[3], giving it knowledge of the preimage
2258                 claim_funds!(nodes[3], nodes[2], payment_preimage_1, payment_hash_1);
2259                 mine_transaction(&nodes[3], &node_txn[0]);
2260                 check_added_monitors!(nodes[3], 1);
2261                 check_preimage_claim(&nodes[3], &node_txn);
2262         }
2263         check_closed_broadcast!(nodes[3], true);
2264         assert_eq!(nodes[2].node.list_channels().len(), 0);
2265         assert_eq!(nodes[3].node.list_channels().len(), 1);
2266         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
2267         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2268
2269         // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2270         // confusing us in the following tests.
2271         let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2272
2273         // One pending HTLC to time out:
2274         let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[3], &[&nodes[4]], 3_000_000);
2275         // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2276         // buffer space).
2277
2278         let (close_chan_update_1, close_chan_update_2) = {
2279                 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2280                 let events = nodes[3].node.get_and_clear_pending_msg_events();
2281                 assert_eq!(events.len(), 2);
2282                 let close_chan_update_1 = match events[0] {
2283                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2284                                 msg.clone()
2285                         },
2286                         _ => panic!("Unexpected event"),
2287                 };
2288                 match events[1] {
2289                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2290                                 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2291                         },
2292                         _ => panic!("Unexpected event"),
2293                 }
2294                 check_added_monitors!(nodes[3], 1);
2295
2296                 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2297                 {
2298                         let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2299                         node_txn.retain(|tx| {
2300                                 if tx.input[0].previous_output.txid == node2_commitment_txid {
2301                                         false
2302                                 } else { true }
2303                         });
2304                 }
2305
2306                 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2307
2308                 // Claim the payment on nodes[4], giving it knowledge of the preimage
2309                 claim_funds!(nodes[4], nodes[3], payment_preimage_2, payment_hash_2);
2310
2311                 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2312                 let events = nodes[4].node.get_and_clear_pending_msg_events();
2313                 assert_eq!(events.len(), 2);
2314                 let close_chan_update_2 = match events[0] {
2315                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2316                                 msg.clone()
2317                         },
2318                         _ => panic!("Unexpected event"),
2319                 };
2320                 match events[1] {
2321                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2322                                 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2323                         },
2324                         _ => panic!("Unexpected event"),
2325                 }
2326                 check_added_monitors!(nodes[4], 1);
2327                 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2328
2329                 mine_transaction(&nodes[4], &node_txn[0]);
2330                 check_preimage_claim(&nodes[4], &node_txn);
2331                 (close_chan_update_1, close_chan_update_2)
2332         };
2333         nodes[3].gossip_sync.handle_channel_update(&close_chan_update_2).unwrap();
2334         nodes[4].gossip_sync.handle_channel_update(&close_chan_update_1).unwrap();
2335         assert_eq!(nodes[3].node.list_channels().len(), 0);
2336         assert_eq!(nodes[4].node.list_channels().len(), 0);
2337
2338         nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon).unwrap();
2339         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2340         check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed);
2341 }
2342
2343 #[test]
2344 fn test_justice_tx() {
2345         // Test justice txn built on revoked HTLC-Success tx, against both sides
2346         let mut alice_config = UserConfig::default();
2347         alice_config.channel_handshake_config.announced_channel = true;
2348         alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2349         alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2350         let mut bob_config = UserConfig::default();
2351         bob_config.channel_handshake_config.announced_channel = true;
2352         bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2353         bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2354         let user_cfgs = [Some(alice_config), Some(bob_config)];
2355         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2356         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2357         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2358         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2359         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2360         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2361         *nodes[0].connect_style.borrow_mut() = ConnectStyle::FullBlockViaListen;
2362         // Create some new channels:
2363         let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2364
2365         // A pending HTLC which will be revoked:
2366         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2367         // Get the will-be-revoked local txn from nodes[0]
2368         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2369         assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2370         assert_eq!(revoked_local_txn[0].input.len(), 1);
2371         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2372         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2373         assert_eq!(revoked_local_txn[1].input.len(), 1);
2374         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2375         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2376         // Revoke the old state
2377         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2378
2379         {
2380                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2381                 {
2382                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2383                         assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2384                         assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2385
2386                         check_spends!(node_txn[0], revoked_local_txn[0]);
2387                         node_txn.swap_remove(0);
2388                         node_txn.truncate(1);
2389                 }
2390                 check_added_monitors!(nodes[1], 1);
2391                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2392                 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2393
2394                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2395                 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2396                 // Verify broadcast of revoked HTLC-timeout
2397                 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2398                 check_added_monitors!(nodes[0], 1);
2399                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2400                 // Broadcast revoked HTLC-timeout on node 1
2401                 mine_transaction(&nodes[1], &node_txn[1]);
2402                 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2403         }
2404         get_announce_close_broadcast_events(&nodes, 0, 1);
2405
2406         assert_eq!(nodes[0].node.list_channels().len(), 0);
2407         assert_eq!(nodes[1].node.list_channels().len(), 0);
2408
2409         // We test justice_tx build by A on B's revoked HTLC-Success tx
2410         // Create some new channels:
2411         let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2412         {
2413                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2414                 node_txn.clear();
2415         }
2416
2417         // A pending HTLC which will be revoked:
2418         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2419         // Get the will-be-revoked local txn from B
2420         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2421         assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2422         assert_eq!(revoked_local_txn[0].input.len(), 1);
2423         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2424         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2425         // Revoke the old state
2426         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2427         {
2428                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2429                 {
2430                         let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2431                         assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2432                         assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2433
2434                         check_spends!(node_txn[0], revoked_local_txn[0]);
2435                         node_txn.swap_remove(0);
2436                 }
2437                 check_added_monitors!(nodes[0], 1);
2438                 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2439
2440                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2441                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2442                 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2443                 check_added_monitors!(nodes[1], 1);
2444                 mine_transaction(&nodes[0], &node_txn[1]);
2445                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2446                 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2447         }
2448         get_announce_close_broadcast_events(&nodes, 0, 1);
2449         assert_eq!(nodes[0].node.list_channels().len(), 0);
2450         assert_eq!(nodes[1].node.list_channels().len(), 0);
2451 }
2452
2453 #[test]
2454 fn revoked_output_claim() {
2455         // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2456         // transaction is broadcast by its counterparty
2457         let chanmon_cfgs = create_chanmon_cfgs(2);
2458         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2459         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2460         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2461         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2462         // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2463         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2464         assert_eq!(revoked_local_txn.len(), 1);
2465         // Only output is the full channel value back to nodes[0]:
2466         assert_eq!(revoked_local_txn[0].output.len(), 1);
2467         // Send a payment through, updating everyone's latest commitment txn
2468         send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2469
2470         // Inform nodes[1] that nodes[0] broadcast a stale tx
2471         mine_transaction(&nodes[1], &revoked_local_txn[0]);
2472         check_added_monitors!(nodes[1], 1);
2473         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2474         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2475         assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2476
2477         check_spends!(node_txn[0], revoked_local_txn[0]);
2478         check_spends!(node_txn[1], chan_1.3);
2479
2480         // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2481         mine_transaction(&nodes[0], &revoked_local_txn[0]);
2482         get_announce_close_broadcast_events(&nodes, 0, 1);
2483         check_added_monitors!(nodes[0], 1);
2484         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2485 }
2486
2487 #[test]
2488 fn claim_htlc_outputs_shared_tx() {
2489         // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2490         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2491         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2492         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2493         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2494         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2495
2496         // Create some new channel:
2497         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2498
2499         // Rebalance the network to generate htlc in the two directions
2500         send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2501         // 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
2502         let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2503         let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2504
2505         // Get the will-be-revoked local txn from node[0]
2506         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2507         assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2508         assert_eq!(revoked_local_txn[0].input.len(), 1);
2509         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2510         assert_eq!(revoked_local_txn[1].input.len(), 1);
2511         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2512         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2513         check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2514
2515         //Revoke the old state
2516         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2517
2518         {
2519                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2520                 check_added_monitors!(nodes[0], 1);
2521                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2522                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2523                 check_added_monitors!(nodes[1], 1);
2524                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2525                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2526                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2527
2528                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2529                 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment
2530
2531                 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2532                 check_spends!(node_txn[0], revoked_local_txn[0]);
2533
2534                 let mut witness_lens = BTreeSet::new();
2535                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2536                 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2537                 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2538                 assert_eq!(witness_lens.len(), 3);
2539                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2540                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2541                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2542
2543                 // Next nodes[1] broadcasts its current local tx state:
2544                 assert_eq!(node_txn[1].input.len(), 1);
2545                 check_spends!(node_txn[1], chan_1.3);
2546
2547                 // Finally, mine the penalty transaction and check that we get an HTLC failure after
2548                 // ANTI_REORG_DELAY confirmations.
2549                 mine_transaction(&nodes[1], &node_txn[0]);
2550                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2551                 expect_payment_failed!(nodes[1], payment_hash_2, false);
2552         }
2553         get_announce_close_broadcast_events(&nodes, 0, 1);
2554         assert_eq!(nodes[0].node.list_channels().len(), 0);
2555         assert_eq!(nodes[1].node.list_channels().len(), 0);
2556 }
2557
2558 #[test]
2559 fn claim_htlc_outputs_single_tx() {
2560         // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2561         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2562         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2563         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2564         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2565         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2566
2567         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2568
2569         // Rebalance the network to generate htlc in the two directions
2570         send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2571         // 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
2572         // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2573         let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2574         let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2575
2576         // Get the will-be-revoked local txn from node[0]
2577         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2578
2579         //Revoke the old state
2580         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2581
2582         {
2583                 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2584                 check_added_monitors!(nodes[0], 1);
2585                 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2586                 check_added_monitors!(nodes[1], 1);
2587                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2588                 let mut events = nodes[0].node.get_and_clear_pending_events();
2589                 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2590                 match events.last().unwrap() {
2591                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2592                         _ => panic!("Unexpected event"),
2593                 }
2594
2595                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2596                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2597
2598                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2599                 assert!(node_txn.len() == 9 || node_txn.len() == 10);
2600
2601                 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2602                 assert_eq!(node_txn[0].input.len(), 1);
2603                 check_spends!(node_txn[0], chan_1.3);
2604                 assert_eq!(node_txn[1].input.len(), 1);
2605                 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2606                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2607                 check_spends!(node_txn[1], node_txn[0]);
2608
2609                 // Justice transactions are indices 1-2-4
2610                 assert_eq!(node_txn[2].input.len(), 1);
2611                 assert_eq!(node_txn[3].input.len(), 1);
2612                 assert_eq!(node_txn[4].input.len(), 1);
2613
2614                 check_spends!(node_txn[2], revoked_local_txn[0]);
2615                 check_spends!(node_txn[3], revoked_local_txn[0]);
2616                 check_spends!(node_txn[4], revoked_local_txn[0]);
2617
2618                 let mut witness_lens = BTreeSet::new();
2619                 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2620                 witness_lens.insert(node_txn[3].input[0].witness.last().unwrap().len());
2621                 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2622                 assert_eq!(witness_lens.len(), 3);
2623                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2624                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2625                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2626
2627                 // Finally, mine the penalty transactions and check that we get an HTLC failure after
2628                 // ANTI_REORG_DELAY confirmations.
2629                 mine_transaction(&nodes[1], &node_txn[2]);
2630                 mine_transaction(&nodes[1], &node_txn[3]);
2631                 mine_transaction(&nodes[1], &node_txn[4]);
2632                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2633                 expect_payment_failed!(nodes[1], payment_hash_2, false);
2634         }
2635         get_announce_close_broadcast_events(&nodes, 0, 1);
2636         assert_eq!(nodes[0].node.list_channels().len(), 0);
2637         assert_eq!(nodes[1].node.list_channels().len(), 0);
2638 }
2639
2640 #[test]
2641 fn test_htlc_on_chain_success() {
2642         // Test that in case of a unilateral close onchain, we detect the state of output and pass
2643         // the preimage backward accordingly. So here we test that ChannelManager is
2644         // broadcasting the right event to other nodes in payment path.
2645         // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2646         // A --------------------> B ----------------------> C (preimage)
2647         // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2648         // commitment transaction was broadcast.
2649         // Then, B should learn the preimage from said transactions, attempting to claim backwards
2650         // towards B.
2651         // B should be able to claim via preimage if A then broadcasts its local tx.
2652         // Finally, when A sees B's latest local commitment transaction it should be able to claim
2653         // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2654         // PaymentSent event).
2655
2656         let chanmon_cfgs = create_chanmon_cfgs(3);
2657         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2658         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2659         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2660
2661         // Create some initial channels
2662         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2663         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2664
2665         // Ensure all nodes are at the same height
2666         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2667         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2668         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2669         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2670
2671         // Rebalance the network a bit by relaying one payment through all the channels...
2672         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2673         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2674
2675         let (our_payment_preimage, payment_hash_1, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2676         let (our_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2677
2678         // Broadcast legit commitment tx from C on B's chain
2679         // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2680         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2681         assert_eq!(commitment_tx.len(), 1);
2682         check_spends!(commitment_tx[0], chan_2.3);
2683         nodes[2].node.claim_funds(our_payment_preimage);
2684         expect_payment_claimed!(nodes[2], payment_hash_1, 3_000_000);
2685         nodes[2].node.claim_funds(our_payment_preimage_2);
2686         expect_payment_claimed!(nodes[2], payment_hash_2, 3_000_000);
2687         check_added_monitors!(nodes[2], 2);
2688         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2689         assert!(updates.update_add_htlcs.is_empty());
2690         assert!(updates.update_fail_htlcs.is_empty());
2691         assert!(updates.update_fail_malformed_htlcs.is_empty());
2692         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2693
2694         mine_transaction(&nodes[2], &commitment_tx[0]);
2695         check_closed_broadcast!(nodes[2], true);
2696         check_added_monitors!(nodes[2], 1);
2697         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2698         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)
2699         assert_eq!(node_txn.len(), 5);
2700         assert_eq!(node_txn[0], node_txn[3]);
2701         assert_eq!(node_txn[1], node_txn[4]);
2702         assert_eq!(node_txn[2], commitment_tx[0]);
2703         check_spends!(node_txn[0], commitment_tx[0]);
2704         check_spends!(node_txn[1], commitment_tx[0]);
2705         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2706         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2707         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2708         assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2709         assert_eq!(node_txn[0].lock_time.0, 0);
2710         assert_eq!(node_txn[1].lock_time.0, 0);
2711
2712         // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2713         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
2714         connect_block(&nodes[1], &Block { header, txdata: node_txn});
2715         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2716         {
2717                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2718                 assert_eq!(added_monitors.len(), 1);
2719                 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2720                 added_monitors.clear();
2721         }
2722         let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2723         assert_eq!(forwarded_events.len(), 3);
2724         match forwarded_events[0] {
2725                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2726                 _ => panic!("Unexpected event"),
2727         }
2728         let chan_id = Some(chan_1.2);
2729         match forwarded_events[1] {
2730                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
2731                         assert_eq!(fee_earned_msat, Some(1000));
2732                         assert_eq!(prev_channel_id, chan_id);
2733                         assert_eq!(claim_from_onchain_tx, true);
2734                         assert_eq!(next_channel_id, Some(chan_2.2));
2735                 },
2736                 _ => panic!()
2737         }
2738         match forwarded_events[2] {
2739                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
2740                         assert_eq!(fee_earned_msat, Some(1000));
2741                         assert_eq!(prev_channel_id, chan_id);
2742                         assert_eq!(claim_from_onchain_tx, true);
2743                         assert_eq!(next_channel_id, Some(chan_2.2));
2744                 },
2745                 _ => panic!()
2746         }
2747         let events = nodes[1].node.get_and_clear_pending_msg_events();
2748         {
2749                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2750                 assert_eq!(added_monitors.len(), 2);
2751                 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2752                 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2753                 added_monitors.clear();
2754         }
2755         assert_eq!(events.len(), 3);
2756         match events[0] {
2757                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2758                 _ => panic!("Unexpected event"),
2759         }
2760         match events[1] {
2761                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2762                 _ => panic!("Unexpected event"),
2763         }
2764
2765         match events[2] {
2766                 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, .. } } => {
2767                         assert!(update_add_htlcs.is_empty());
2768                         assert!(update_fail_htlcs.is_empty());
2769                         assert_eq!(update_fulfill_htlcs.len(), 1);
2770                         assert!(update_fail_malformed_htlcs.is_empty());
2771                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2772                 },
2773                 _ => panic!("Unexpected event"),
2774         };
2775         macro_rules! check_tx_local_broadcast {
2776                 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2777                         let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2778                         assert_eq!(node_txn.len(), 3);
2779                         // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2780                         // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2781                         check_spends!(node_txn[1], $commitment_tx);
2782                         check_spends!(node_txn[2], $commitment_tx);
2783                         assert_ne!(node_txn[1].lock_time.0, 0);
2784                         assert_ne!(node_txn[2].lock_time.0, 0);
2785                         if $htlc_offered {
2786                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2787                                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2788                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2789                                 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2790                         } else {
2791                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2792                                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2793                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2794                                 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2795                         }
2796                         check_spends!(node_txn[0], $chan_tx);
2797                         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2798                         node_txn.clear();
2799                 } }
2800         }
2801         // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2802         // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2803         // timeout-claim of the output that nodes[2] just claimed via success.
2804         check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2805
2806         // Broadcast legit commitment tx from A on B's chain
2807         // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
2808         let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2809         check_spends!(node_a_commitment_tx[0], chan_1.3);
2810         mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2811         check_closed_broadcast!(nodes[1], true);
2812         check_added_monitors!(nodes[1], 1);
2813         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2814         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2815         assert_eq!(node_txn.len(), 6); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 3 (HTLC-Success, 2* RBF bumps of above HTLC txn)
2816         let commitment_spend =
2817                 if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2818                         check_spends!(node_txn[1], commitment_tx[0]);
2819                         check_spends!(node_txn[2], commitment_tx[0]);
2820                         assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2821                         &node_txn[0]
2822                 } else {
2823                         check_spends!(node_txn[0], commitment_tx[0]);
2824                         check_spends!(node_txn[1], commitment_tx[0]);
2825                         assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2826                         &node_txn[2]
2827                 };
2828
2829         check_spends!(commitment_spend, node_a_commitment_tx[0]);
2830         assert_eq!(commitment_spend.input.len(), 2);
2831         assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2832         assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2833         assert_eq!(commitment_spend.lock_time.0, 0);
2834         assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2835         check_spends!(node_txn[3], chan_1.3);
2836         assert_eq!(node_txn[3].input[0].witness.clone().last().unwrap().len(), 71);
2837         check_spends!(node_txn[4], node_txn[3]);
2838         check_spends!(node_txn[5], node_txn[3]);
2839         // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2840         // we already checked the same situation with A.
2841
2842         // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2843         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
2844         connect_block(&nodes[0], &Block { header, txdata: vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()] });
2845         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2846         check_closed_broadcast!(nodes[0], true);
2847         check_added_monitors!(nodes[0], 1);
2848         let events = nodes[0].node.get_and_clear_pending_events();
2849         assert_eq!(events.len(), 5);
2850         let mut first_claimed = false;
2851         for event in events {
2852                 match event {
2853                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
2854                                 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
2855                                         assert!(!first_claimed);
2856                                         first_claimed = true;
2857                                 } else {
2858                                         assert_eq!(payment_preimage, our_payment_preimage_2);
2859                                         assert_eq!(payment_hash, payment_hash_2);
2860                                 }
2861                         },
2862                         Event::PaymentPathSuccessful { .. } => {},
2863                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
2864                         _ => panic!("Unexpected event"),
2865                 }
2866         }
2867         check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0], chan_1.3);
2868 }
2869
2870 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2871         // Test that in case of a unilateral close onchain, we detect the state of output and
2872         // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2873         // broadcasting the right event to other nodes in payment path.
2874         // A ------------------> B ----------------------> C (timeout)
2875         //    B's commitment tx                 C's commitment tx
2876         //            \                                  \
2877         //         B's HTLC timeout tx               B's timeout tx
2878
2879         let chanmon_cfgs = create_chanmon_cfgs(3);
2880         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2881         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2882         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2883         *nodes[0].connect_style.borrow_mut() = connect_style;
2884         *nodes[1].connect_style.borrow_mut() = connect_style;
2885         *nodes[2].connect_style.borrow_mut() = connect_style;
2886
2887         // Create some intial channels
2888         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2889         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2890
2891         // Rebalance the network a bit by relaying one payment thorugh all the channels...
2892         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2893         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2894
2895         let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2896
2897         // Broadcast legit commitment tx from C on B's chain
2898         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2899         check_spends!(commitment_tx[0], chan_2.3);
2900         nodes[2].node.fail_htlc_backwards(&payment_hash);
2901         check_added_monitors!(nodes[2], 0);
2902         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }]);
2903         check_added_monitors!(nodes[2], 1);
2904
2905         let events = nodes[2].node.get_and_clear_pending_msg_events();
2906         assert_eq!(events.len(), 1);
2907         match events[0] {
2908                 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, .. } } => {
2909                         assert!(update_add_htlcs.is_empty());
2910                         assert!(!update_fail_htlcs.is_empty());
2911                         assert!(update_fulfill_htlcs.is_empty());
2912                         assert!(update_fail_malformed_htlcs.is_empty());
2913                         assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2914                 },
2915                 _ => panic!("Unexpected event"),
2916         };
2917         mine_transaction(&nodes[2], &commitment_tx[0]);
2918         check_closed_broadcast!(nodes[2], true);
2919         check_added_monitors!(nodes[2], 1);
2920         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2921         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2922         assert_eq!(node_txn.len(), 1);
2923         check_spends!(node_txn[0], chan_2.3);
2924         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2925
2926         // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2927         // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2928         connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2929         mine_transaction(&nodes[1], &commitment_tx[0]);
2930         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2931         let timeout_tx;
2932         {
2933                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2934                 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
2935                 assert_eq!(node_txn[0], node_txn[3]);
2936                 assert_eq!(node_txn[1], node_txn[4]);
2937
2938                 check_spends!(node_txn[2], commitment_tx[0]);
2939                 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2940
2941                 check_spends!(node_txn[0], chan_2.3);
2942                 check_spends!(node_txn[1], node_txn[0]);
2943                 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2944                 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2945
2946                 timeout_tx = node_txn[2].clone();
2947                 node_txn.clear();
2948         }
2949
2950         mine_transaction(&nodes[1], &timeout_tx);
2951         check_added_monitors!(nodes[1], 1);
2952         check_closed_broadcast!(nodes[1], true);
2953         {
2954                 // B will rebroadcast a fee-bumped timeout transaction here.
2955                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2956                 assert_eq!(node_txn.len(), 1);
2957                 check_spends!(node_txn[0], commitment_tx[0]);
2958         }
2959
2960         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2961         {
2962                 // B may rebroadcast its own holder commitment transaction here, as a safeguard against
2963                 // some incredibly unlikely partial-eclipse-attack scenarios. That said, because the
2964                 // original commitment_tx[0] (also spending chan_2.3) has reached ANTI_REORG_DELAY B really
2965                 // shouldn't broadcast anything here, and in some connect style scenarios we do not.
2966                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2967                 if node_txn.len() == 1 {
2968                         check_spends!(node_txn[0], chan_2.3);
2969                 } else {
2970                         assert_eq!(node_txn.len(), 0);
2971                 }
2972         }
2973
2974         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
2975         check_added_monitors!(nodes[1], 1);
2976         let events = nodes[1].node.get_and_clear_pending_msg_events();
2977         assert_eq!(events.len(), 1);
2978         match events[0] {
2979                 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, .. } } => {
2980                         assert!(update_add_htlcs.is_empty());
2981                         assert!(!update_fail_htlcs.is_empty());
2982                         assert!(update_fulfill_htlcs.is_empty());
2983                         assert!(update_fail_malformed_htlcs.is_empty());
2984                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2985                 },
2986                 _ => panic!("Unexpected event"),
2987         };
2988
2989         // Broadcast legit commitment tx from B on A's chain
2990         let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
2991         check_spends!(commitment_tx[0], chan_1.3);
2992
2993         mine_transaction(&nodes[0], &commitment_tx[0]);
2994         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2995
2996         check_closed_broadcast!(nodes[0], true);
2997         check_added_monitors!(nodes[0], 1);
2998         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2999         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 commitment tx, ChannelMonitor : 1 timeout tx
3000         assert_eq!(node_txn.len(), 2);
3001         check_spends!(node_txn[0], chan_1.3);
3002         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
3003         check_spends!(node_txn[1], commitment_tx[0]);
3004         assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3005 }
3006
3007 #[test]
3008 fn test_htlc_on_chain_timeout() {
3009         do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
3010         do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
3011         do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
3012 }
3013
3014 #[test]
3015 fn test_simple_commitment_revoked_fail_backward() {
3016         // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3017         // and fail backward accordingly.
3018
3019         let chanmon_cfgs = create_chanmon_cfgs(3);
3020         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3021         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3022         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3023
3024         // Create some initial channels
3025         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3026         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3027
3028         let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3029         // Get the will-be-revoked local txn from nodes[2]
3030         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3031         // Revoke the old state
3032         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3033
3034         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3035
3036         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3037         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3038         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3039         check_added_monitors!(nodes[1], 1);
3040         check_closed_broadcast!(nodes[1], true);
3041
3042         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
3043         check_added_monitors!(nodes[1], 1);
3044         let events = nodes[1].node.get_and_clear_pending_msg_events();
3045         assert_eq!(events.len(), 1);
3046         match events[0] {
3047                 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, .. } } => {
3048                         assert!(update_add_htlcs.is_empty());
3049                         assert_eq!(update_fail_htlcs.len(), 1);
3050                         assert!(update_fulfill_htlcs.is_empty());
3051                         assert!(update_fail_malformed_htlcs.is_empty());
3052                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3053
3054                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3055                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3056                         expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3057                 },
3058                 _ => panic!("Unexpected event"),
3059         }
3060 }
3061
3062 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3063         // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3064         // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3065         // commitment transaction anymore.
3066         // To do this, we have the peer which will broadcast a revoked commitment transaction send
3067         // a number of update_fail/commitment_signed updates without ever sending the RAA in
3068         // response to our commitment_signed. This is somewhat misbehavior-y, though not
3069         // technically disallowed and we should probably handle it reasonably.
3070         // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3071         // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3072         // transactions:
3073         // * Once we move it out of our holding cell/add it, we will immediately include it in a
3074         //   commitment_signed (implying it will be in the latest remote commitment transaction).
3075         // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3076         //   and once they revoke the previous commitment transaction (allowing us to send a new
3077         //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3078         let chanmon_cfgs = create_chanmon_cfgs(3);
3079         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3080         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3081         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3082
3083         // Create some initial channels
3084         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3085         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3086
3087         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 });
3088         // Get the will-be-revoked local txn from nodes[2]
3089         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3090         assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3091         // Revoke the old state
3092         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3093
3094         let value = if use_dust {
3095                 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3096                 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3097                 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3098         } else { 3000000 };
3099
3100         let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3101         let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3102         let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3103
3104         nodes[2].node.fail_htlc_backwards(&first_payment_hash);
3105         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
3106         check_added_monitors!(nodes[2], 1);
3107         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3108         assert!(updates.update_add_htlcs.is_empty());
3109         assert!(updates.update_fulfill_htlcs.is_empty());
3110         assert!(updates.update_fail_malformed_htlcs.is_empty());
3111         assert_eq!(updates.update_fail_htlcs.len(), 1);
3112         assert!(updates.update_fee.is_none());
3113         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3114         let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3115         // Drop the last RAA from 3 -> 2
3116
3117         nodes[2].node.fail_htlc_backwards(&second_payment_hash);
3118         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: second_payment_hash }]);
3119         check_added_monitors!(nodes[2], 1);
3120         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3121         assert!(updates.update_add_htlcs.is_empty());
3122         assert!(updates.update_fulfill_htlcs.is_empty());
3123         assert!(updates.update_fail_malformed_htlcs.is_empty());
3124         assert_eq!(updates.update_fail_htlcs.len(), 1);
3125         assert!(updates.update_fee.is_none());
3126         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3127         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3128         check_added_monitors!(nodes[1], 1);
3129         // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3130         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3131         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3132         check_added_monitors!(nodes[2], 1);
3133
3134         nodes[2].node.fail_htlc_backwards(&third_payment_hash);
3135         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: third_payment_hash }]);
3136         check_added_monitors!(nodes[2], 1);
3137         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3138         assert!(updates.update_add_htlcs.is_empty());
3139         assert!(updates.update_fulfill_htlcs.is_empty());
3140         assert!(updates.update_fail_malformed_htlcs.is_empty());
3141         assert_eq!(updates.update_fail_htlcs.len(), 1);
3142         assert!(updates.update_fee.is_none());
3143         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3144         // At this point first_payment_hash has dropped out of the latest two commitment
3145         // transactions that nodes[1] is tracking...
3146         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3147         check_added_monitors!(nodes[1], 1);
3148         // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3149         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3150         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3151         check_added_monitors!(nodes[2], 1);
3152
3153         // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3154         // on nodes[2]'s RAA.
3155         let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3156         nodes[1].node.send_payment(&route, fourth_payment_hash, &Some(fourth_payment_secret)).unwrap();
3157         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3158         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3159         check_added_monitors!(nodes[1], 0);
3160
3161         if deliver_bs_raa {
3162                 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3163                 // One monitor for the new revocation preimage, no second on as we won't generate a new
3164                 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3165                 check_added_monitors!(nodes[1], 1);
3166                 let events = nodes[1].node.get_and_clear_pending_events();
3167                 assert_eq!(events.len(), 2);
3168                 match events[0] {
3169                         Event::PendingHTLCsForwardable { .. } => { },
3170                         _ => panic!("Unexpected event"),
3171                 };
3172                 match events[1] {
3173                         Event::HTLCHandlingFailed { .. } => { },
3174                         _ => panic!("Unexpected event"),
3175                 }
3176                 // Deliberately don't process the pending fail-back so they all fail back at once after
3177                 // block connection just like the !deliver_bs_raa case
3178         }
3179
3180         let mut failed_htlcs = HashSet::new();
3181         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3182
3183         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3184         check_added_monitors!(nodes[1], 1);
3185         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3186         assert!(ANTI_REORG_DELAY > PAYMENT_EXPIRY_BLOCKS); // We assume payments will also expire
3187
3188         let events = nodes[1].node.get_and_clear_pending_events();
3189         assert_eq!(events.len(), if deliver_bs_raa { 2 + (nodes.len() - 1) } else { 4 + nodes.len() });
3190         match events[0] {
3191                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3192                 _ => panic!("Unexepected event"),
3193         }
3194         match events[1] {
3195                 Event::PaymentPathFailed { ref payment_hash, .. } => {
3196                         assert_eq!(*payment_hash, fourth_payment_hash);
3197                 },
3198                 _ => panic!("Unexpected event"),
3199         }
3200         if !deliver_bs_raa {
3201                 match events[2] {
3202                         Event::PaymentFailed { ref payment_hash, .. } => {
3203                                 assert_eq!(*payment_hash, fourth_payment_hash);
3204                         },
3205                         _ => panic!("Unexpected event"),
3206                 }
3207                 match events[3] {
3208                         Event::PendingHTLCsForwardable { .. } => { },
3209                         _ => panic!("Unexpected event"),
3210                 };
3211         }
3212         nodes[1].node.process_pending_htlc_forwards();
3213         check_added_monitors!(nodes[1], 1);
3214
3215         let events = nodes[1].node.get_and_clear_pending_msg_events();
3216         assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3217         match events[if deliver_bs_raa { 1 } else { 0 }] {
3218                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3219                 _ => panic!("Unexpected event"),
3220         }
3221         match events[if deliver_bs_raa { 2 } else { 1 }] {
3222                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3223                         assert_eq!(channel_id, chan_2.2);
3224                         assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3225                 },
3226                 _ => panic!("Unexpected event"),
3227         }
3228         if deliver_bs_raa {
3229                 match events[0] {
3230                         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, .. } } => {
3231                                 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3232                                 assert_eq!(update_add_htlcs.len(), 1);
3233                                 assert!(update_fulfill_htlcs.is_empty());
3234                                 assert!(update_fail_htlcs.is_empty());
3235                                 assert!(update_fail_malformed_htlcs.is_empty());
3236                         },
3237                         _ => panic!("Unexpected event"),
3238                 }
3239         }
3240         match events[if deliver_bs_raa { 3 } else { 2 }] {
3241                 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, .. } } => {
3242                         assert!(update_add_htlcs.is_empty());
3243                         assert_eq!(update_fail_htlcs.len(), 3);
3244                         assert!(update_fulfill_htlcs.is_empty());
3245                         assert!(update_fail_malformed_htlcs.is_empty());
3246                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3247
3248                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3249                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3250                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3251
3252                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3253
3254                         let events = nodes[0].node.get_and_clear_pending_events();
3255                         assert_eq!(events.len(), 3);
3256                         match events[0] {
3257                                 Event::PaymentPathFailed { ref payment_hash, ref network_update, .. } => {
3258                                         assert!(failed_htlcs.insert(payment_hash.0));
3259                                         // If we delivered B's RAA we got an unknown preimage error, not something
3260                                         // that we should update our routing table for.
3261                                         if !deliver_bs_raa {
3262                                                 assert!(network_update.is_some());
3263                                         }
3264                                 },
3265                                 _ => panic!("Unexpected event"),
3266                         }
3267                         match events[1] {
3268                                 Event::PaymentPathFailed { ref payment_hash, ref network_update, .. } => {
3269                                         assert!(failed_htlcs.insert(payment_hash.0));
3270                                         assert!(network_update.is_some());
3271                                 },
3272                                 _ => panic!("Unexpected event"),
3273                         }
3274                         match events[2] {
3275                                 Event::PaymentPathFailed { ref payment_hash, ref network_update, .. } => {
3276                                         assert!(failed_htlcs.insert(payment_hash.0));
3277                                         assert!(network_update.is_some());
3278                                 },
3279                                 _ => panic!("Unexpected event"),
3280                         }
3281                 },
3282                 _ => panic!("Unexpected event"),
3283         }
3284
3285         assert!(failed_htlcs.contains(&first_payment_hash.0));
3286         assert!(failed_htlcs.contains(&second_payment_hash.0));
3287         assert!(failed_htlcs.contains(&third_payment_hash.0));
3288 }
3289
3290 #[test]
3291 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3292         do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3293         do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3294         do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3295         do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3296 }
3297
3298 #[test]
3299 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3300         do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3301         do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3302         do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3303         do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3304 }
3305
3306 #[test]
3307 fn fail_backward_pending_htlc_upon_channel_failure() {
3308         let chanmon_cfgs = create_chanmon_cfgs(2);
3309         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3310         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3311         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3312         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3313
3314         // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3315         {
3316                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3317                 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
3318                 check_added_monitors!(nodes[0], 1);
3319
3320                 let payment_event = {
3321                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3322                         assert_eq!(events.len(), 1);
3323                         SendEvent::from_event(events.remove(0))
3324                 };
3325                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3326                 assert_eq!(payment_event.msgs.len(), 1);
3327         }
3328
3329         // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3330         let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3331         {
3332                 nodes[0].node.send_payment(&route, failed_payment_hash, &Some(failed_payment_secret)).unwrap();
3333                 check_added_monitors!(nodes[0], 0);
3334
3335                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3336         }
3337
3338         // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3339         {
3340                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3341
3342                 let secp_ctx = Secp256k1::new();
3343                 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3344                 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3345                 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &Some(payment_secret), current_height, &None).unwrap();
3346                 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3347                 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3348
3349                 // Send a 0-msat update_add_htlc to fail the channel.
3350                 let update_add_htlc = msgs::UpdateAddHTLC {
3351                         channel_id: chan.2,
3352                         htlc_id: 0,
3353                         amount_msat: 0,
3354                         payment_hash,
3355                         cltv_expiry,
3356                         onion_routing_packet,
3357                 };
3358                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3359         }
3360         let events = nodes[0].node.get_and_clear_pending_events();
3361         assert_eq!(events.len(), 2);
3362         // Check that Alice fails backward the pending HTLC from the second payment.
3363         match events[0] {
3364                 Event::PaymentPathFailed { payment_hash, .. } => {
3365                         assert_eq!(payment_hash, failed_payment_hash);
3366                 },
3367                 _ => panic!("Unexpected event"),
3368         }
3369         match events[1] {
3370                 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3371                         assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3372                 },
3373                 _ => panic!("Unexpected event {:?}", events[1]),
3374         }
3375         check_closed_broadcast!(nodes[0], true);
3376         check_added_monitors!(nodes[0], 1);
3377 }
3378
3379 #[test]
3380 fn test_htlc_ignore_latest_remote_commitment() {
3381         // Test that HTLC transactions spending the latest remote commitment transaction are simply
3382         // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3383         let chanmon_cfgs = create_chanmon_cfgs(2);
3384         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3385         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3386         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3387         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3388
3389         route_payment(&nodes[0], &[&nodes[1]], 10000000);
3390         nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3391         connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3392         check_closed_broadcast!(nodes[0], true);
3393         check_added_monitors!(nodes[0], 1);
3394         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
3395
3396         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3397         assert_eq!(node_txn.len(), 3);
3398         assert_eq!(node_txn[0], node_txn[1]);
3399
3400         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
3401         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3402         check_closed_broadcast!(nodes[1], true);
3403         check_added_monitors!(nodes[1], 1);
3404         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3405
3406         // Duplicate the connect_block call since this may happen due to other listeners
3407         // registering new transactions
3408         header.prev_blockhash = header.block_hash();
3409         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[2].clone()]});
3410 }
3411
3412 #[test]
3413 fn test_force_close_fail_back() {
3414         // Check which HTLCs are failed-backwards on channel force-closure
3415         let chanmon_cfgs = create_chanmon_cfgs(3);
3416         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3417         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3418         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3419         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3420         create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3421
3422         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3423
3424         let mut payment_event = {
3425                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
3426                 check_added_monitors!(nodes[0], 1);
3427
3428                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3429                 assert_eq!(events.len(), 1);
3430                 SendEvent::from_event(events.remove(0))
3431         };
3432
3433         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3434         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3435
3436         expect_pending_htlcs_forwardable!(nodes[1]);
3437
3438         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3439         assert_eq!(events_2.len(), 1);
3440         payment_event = SendEvent::from_event(events_2.remove(0));
3441         assert_eq!(payment_event.msgs.len(), 1);
3442
3443         check_added_monitors!(nodes[1], 1);
3444         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3445         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3446         check_added_monitors!(nodes[2], 1);
3447         let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3448
3449         // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3450         // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3451         // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3452
3453         nodes[2].node.force_close_broadcasting_latest_txn(&payment_event.commitment_msg.channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3454         check_closed_broadcast!(nodes[2], true);
3455         check_added_monitors!(nodes[2], 1);
3456         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
3457         let tx = {
3458                 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3459                 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3460                 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3461                 // back to nodes[1] upon timeout otherwise.
3462                 assert_eq!(node_txn.len(), 1);
3463                 node_txn.remove(0)
3464         };
3465
3466         mine_transaction(&nodes[1], &tx);
3467
3468         // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3469         check_closed_broadcast!(nodes[1], true);
3470         check_added_monitors!(nodes[1], 1);
3471         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3472
3473         // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3474         {
3475                 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3476                         .provide_payment_preimage(&our_payment_hash, &our_payment_preimage, &node_cfgs[2].tx_broadcaster, &LowerBoundedFeeEstimator::new(node_cfgs[2].fee_estimator), &node_cfgs[2].logger);
3477         }
3478         mine_transaction(&nodes[2], &tx);
3479         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3480         assert_eq!(node_txn.len(), 1);
3481         assert_eq!(node_txn[0].input.len(), 1);
3482         assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3483         assert_eq!(node_txn[0].lock_time.0, 0); // Must be an HTLC-Success
3484         assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3485
3486         check_spends!(node_txn[0], tx);
3487 }
3488
3489 #[test]
3490 fn test_dup_events_on_peer_disconnect() {
3491         // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3492         // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3493         // as we used to generate the event immediately upon receipt of the payment preimage in the
3494         // update_fulfill_htlc message.
3495
3496         let chanmon_cfgs = create_chanmon_cfgs(2);
3497         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3498         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3499         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3500         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3501
3502         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3503
3504         nodes[1].node.claim_funds(payment_preimage);
3505         expect_payment_claimed!(nodes[1], payment_hash, 1_000_000);
3506         check_added_monitors!(nodes[1], 1);
3507         let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3508         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3509         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
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
3514         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3515         expect_payment_path_successful!(nodes[0]);
3516 }
3517
3518 #[test]
3519 fn test_peer_disconnected_before_funding_broadcasted() {
3520         // Test that channels are closed with `ClosureReason::DisconnectedPeer` if the peer disconnects
3521         // before the funding transaction has been broadcasted.
3522         let chanmon_cfgs = create_chanmon_cfgs(2);
3523         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3524         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3525         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3526
3527         // Open a channel between `nodes[0]` and `nodes[1]`, for which the funding transaction is never
3528         // broadcasted, even though it's created by `nodes[0]`.
3529         let expected_temporary_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
3530         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
3531         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_channel);
3532         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
3533         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_channel);
3534
3535         let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
3536         assert_eq!(temporary_channel_id, expected_temporary_channel_id);
3537
3538         assert!(nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
3539
3540         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
3541         assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
3542
3543         // Even though the funding transaction is created by `nodes[0]`, the `FundingCreated` msg is
3544         // never sent to `nodes[1]`, and therefore the tx is never signed by either party nor
3545         // broadcasted.
3546         {
3547                 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
3548         }
3549
3550         // Ensure that the channel is closed with `ClosureReason::DisconnectedPeer` when the peers are
3551         // disconnected before the funding transaction was broadcasted.
3552         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3553         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3554
3555         check_closed_event!(nodes[0], 1, ClosureReason::DisconnectedPeer);
3556         check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
3557 }
3558
3559 #[test]
3560 fn test_simple_peer_disconnect() {
3561         // Test that we can reconnect when there are no lost messages
3562         let chanmon_cfgs = create_chanmon_cfgs(3);
3563         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3564         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3565         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3566         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3567         create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3568
3569         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3570         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3571         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3572
3573         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3574         let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3575         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3576         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3577
3578         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3579         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3580         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3581
3582         let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3583         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3584         let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3585         let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3586
3587         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3588         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3589
3590         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3591         fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3592
3593         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3594         {
3595                 let events = nodes[0].node.get_and_clear_pending_events();
3596                 assert_eq!(events.len(), 3);
3597                 match events[0] {
3598                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3599                                 assert_eq!(payment_preimage, payment_preimage_3);
3600                                 assert_eq!(payment_hash, payment_hash_3);
3601                         },
3602                         _ => panic!("Unexpected event"),
3603                 }
3604                 match events[1] {
3605                         Event::PaymentPathFailed { payment_hash, payment_failed_permanently, .. } => {
3606                                 assert_eq!(payment_hash, payment_hash_5);
3607                                 assert!(payment_failed_permanently);
3608                         },
3609                         _ => panic!("Unexpected event"),
3610                 }
3611                 match events[2] {
3612                         Event::PaymentPathSuccessful { .. } => {},
3613                         _ => panic!("Unexpected event"),
3614                 }
3615         }
3616
3617         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3618         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3619 }
3620
3621 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3622         // Test that we can reconnect when in-flight HTLC updates get dropped
3623         let chanmon_cfgs = create_chanmon_cfgs(2);
3624         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3625         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3626         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3627
3628         let mut as_channel_ready = None;
3629         if messages_delivered == 0 {
3630                 let (channel_ready, _, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3631                 as_channel_ready = Some(channel_ready);
3632                 // nodes[1] doesn't receive the channel_ready message (it'll be re-sent on reconnect)
3633                 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3634                 // it before the channel_reestablish message.
3635         } else {
3636                 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3637         }
3638
3639         let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1_000_000);
3640
3641         let payment_event = {
3642                 nodes[0].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)).unwrap();
3643                 check_added_monitors!(nodes[0], 1);
3644
3645                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3646                 assert_eq!(events.len(), 1);
3647                 SendEvent::from_event(events.remove(0))
3648         };
3649         assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3650
3651         if messages_delivered < 2 {
3652                 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3653         } else {
3654                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3655                 if messages_delivered >= 3 {
3656                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3657                         check_added_monitors!(nodes[1], 1);
3658                         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3659
3660                         if messages_delivered >= 4 {
3661                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3662                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3663                                 check_added_monitors!(nodes[0], 1);
3664
3665                                 if messages_delivered >= 5 {
3666                                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3667                                         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3668                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3669                                         check_added_monitors!(nodes[0], 1);
3670
3671                                         if messages_delivered >= 6 {
3672                                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3673                                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3674                                                 check_added_monitors!(nodes[1], 1);
3675                                         }
3676                                 }
3677                         }
3678                 }
3679         }
3680
3681         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3682         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3683         if messages_delivered < 3 {
3684                 if simulate_broken_lnd {
3685                         // lnd has a long-standing bug where they send a channel_ready prior to a
3686                         // channel_reestablish if you reconnect prior to channel_ready time.
3687                         //
3688                         // Here we simulate that behavior, delivering a channel_ready immediately on
3689                         // reconnect. Note that we don't bother skipping the now-duplicate channel_ready sent
3690                         // in `reconnect_nodes` but we currently don't fail based on that.
3691                         //
3692                         // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3693                         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready.as_ref().unwrap().0);
3694                 }
3695                 // Even if the channel_ready messages get exchanged, as long as nothing further was
3696                 // received on either side, both sides will need to resend them.
3697                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3698         } else if messages_delivered == 3 {
3699                 // nodes[0] still wants its RAA + commitment_signed
3700                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3701         } else if messages_delivered == 4 {
3702                 // nodes[0] still wants its commitment_signed
3703                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3704         } else if messages_delivered == 5 {
3705                 // nodes[1] still wants its final RAA
3706                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3707         } else if messages_delivered == 6 {
3708                 // Everything was delivered...
3709                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3710         }
3711
3712         let events_1 = nodes[1].node.get_and_clear_pending_events();
3713         assert_eq!(events_1.len(), 1);
3714         match events_1[0] {
3715                 Event::PendingHTLCsForwardable { .. } => { },
3716                 _ => panic!("Unexpected event"),
3717         };
3718
3719         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3720         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3721         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3722
3723         nodes[1].node.process_pending_htlc_forwards();
3724
3725         let events_2 = nodes[1].node.get_and_clear_pending_events();
3726         assert_eq!(events_2.len(), 1);
3727         match events_2[0] {
3728                 Event::PaymentReceived { ref payment_hash, ref purpose, amount_msat } => {
3729                         assert_eq!(payment_hash_1, *payment_hash);
3730                         assert_eq!(amount_msat, 1_000_000);
3731                         match &purpose {
3732                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3733                                         assert!(payment_preimage.is_none());
3734                                         assert_eq!(payment_secret_1, *payment_secret);
3735                                 },
3736                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
3737                         }
3738                 },
3739                 _ => panic!("Unexpected event"),
3740         }
3741
3742         nodes[1].node.claim_funds(payment_preimage_1);
3743         check_added_monitors!(nodes[1], 1);
3744         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3745
3746         let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3747         assert_eq!(events_3.len(), 1);
3748         let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3749                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3750                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3751                         assert!(updates.update_add_htlcs.is_empty());
3752                         assert!(updates.update_fail_htlcs.is_empty());
3753                         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3754                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3755                         assert!(updates.update_fee.is_none());
3756                         (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3757                 },
3758                 _ => panic!("Unexpected event"),
3759         };
3760
3761         if messages_delivered >= 1 {
3762                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3763
3764                 let events_4 = nodes[0].node.get_and_clear_pending_events();
3765                 assert_eq!(events_4.len(), 1);
3766                 match events_4[0] {
3767                         Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3768                                 assert_eq!(payment_preimage_1, *payment_preimage);
3769                                 assert_eq!(payment_hash_1, *payment_hash);
3770                         },
3771                         _ => panic!("Unexpected event"),
3772                 }
3773
3774                 if messages_delivered >= 2 {
3775                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3776                         check_added_monitors!(nodes[0], 1);
3777                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3778
3779                         if messages_delivered >= 3 {
3780                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3781                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3782                                 check_added_monitors!(nodes[1], 1);
3783
3784                                 if messages_delivered >= 4 {
3785                                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3786                                         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3787                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3788                                         check_added_monitors!(nodes[1], 1);
3789
3790                                         if messages_delivered >= 5 {
3791                                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3792                                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3793                                                 check_added_monitors!(nodes[0], 1);
3794                                         }
3795                                 }
3796                         }
3797                 }
3798         }
3799
3800         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3801         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3802         if messages_delivered < 2 {
3803                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3804                 if messages_delivered < 1 {
3805                         expect_payment_sent!(nodes[0], payment_preimage_1);
3806                 } else {
3807                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3808                 }
3809         } else if messages_delivered == 2 {
3810                 // nodes[0] still wants its RAA + commitment_signed
3811                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3812         } else if messages_delivered == 3 {
3813                 // nodes[0] still wants its commitment_signed
3814                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3815         } else if messages_delivered == 4 {
3816                 // nodes[1] still wants its final RAA
3817                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3818         } else if messages_delivered == 5 {
3819                 // Everything was delivered...
3820                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3821         }
3822
3823         if messages_delivered == 1 || messages_delivered == 2 {
3824                 expect_payment_path_successful!(nodes[0]);
3825         }
3826
3827         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3828         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3829         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3830
3831         if messages_delivered > 2 {
3832                 expect_payment_path_successful!(nodes[0]);
3833         }
3834
3835         // Channel should still work fine...
3836         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3837         let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3838         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3839 }
3840
3841 #[test]
3842 fn test_drop_messages_peer_disconnect_a() {
3843         do_test_drop_messages_peer_disconnect(0, true);
3844         do_test_drop_messages_peer_disconnect(0, false);
3845         do_test_drop_messages_peer_disconnect(1, false);
3846         do_test_drop_messages_peer_disconnect(2, false);
3847 }
3848
3849 #[test]
3850 fn test_drop_messages_peer_disconnect_b() {
3851         do_test_drop_messages_peer_disconnect(3, false);
3852         do_test_drop_messages_peer_disconnect(4, false);
3853         do_test_drop_messages_peer_disconnect(5, false);
3854         do_test_drop_messages_peer_disconnect(6, false);
3855 }
3856
3857 #[test]
3858 fn test_funding_peer_disconnect() {
3859         // Test that we can lock in our funding tx while disconnected
3860         let chanmon_cfgs = create_chanmon_cfgs(2);
3861         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3862         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3863         let persister: test_utils::TestPersister;
3864         let new_chain_monitor: test_utils::TestChainMonitor;
3865         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
3866         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3867         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3868
3869         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3870         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3871
3872         confirm_transaction(&nodes[0], &tx);
3873         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3874         assert!(events_1.is_empty());
3875
3876         reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3877
3878         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3879         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3880
3881         confirm_transaction(&nodes[1], &tx);
3882         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3883         assert!(events_2.is_empty());
3884
3885         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
3886         let as_reestablish = get_chan_reestablish_msgs!(nodes[0], nodes[1]).pop().unwrap();
3887         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
3888         let bs_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]).pop().unwrap();
3889
3890         // nodes[0] hasn't yet received a channel_ready, so it only sends that on reconnect.
3891         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
3892         let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3893         assert_eq!(events_3.len(), 1);
3894         let as_channel_ready = match events_3[0] {
3895                 MessageSendEvent::SendChannelReady { ref node_id, ref msg } => {
3896                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3897                         msg.clone()
3898                 },
3899                 _ => panic!("Unexpected event {:?}", events_3[0]),
3900         };
3901
3902         // nodes[1] received nodes[0]'s channel_ready on the first reconnect above, so it should send
3903         // announcement_signatures as well as channel_update.
3904         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reestablish);
3905         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3906         assert_eq!(events_4.len(), 3);
3907         let chan_id;
3908         let bs_channel_ready = match events_4[0] {
3909                 MessageSendEvent::SendChannelReady { ref node_id, ref msg } => {
3910                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3911                         chan_id = msg.channel_id;
3912                         msg.clone()
3913                 },
3914                 _ => panic!("Unexpected event {:?}", events_4[0]),
3915         };
3916         let bs_announcement_sigs = match events_4[1] {
3917                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3918                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3919                         msg.clone()
3920                 },
3921                 _ => panic!("Unexpected event {:?}", events_4[1]),
3922         };
3923         match events_4[2] {
3924                 MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } => {
3925                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3926                 },
3927                 _ => panic!("Unexpected event {:?}", events_4[2]),
3928         }
3929
3930         // Re-deliver nodes[0]'s channel_ready, which nodes[1] can safely ignore. It currently
3931         // generates a duplicative private channel_update
3932         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
3933         let events_5 = nodes[1].node.get_and_clear_pending_msg_events();
3934         assert_eq!(events_5.len(), 1);
3935         match events_5[0] {
3936                 MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } => {
3937                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3938                 },
3939                 _ => panic!("Unexpected event {:?}", events_5[0]),
3940         };
3941
3942         // When we deliver nodes[1]'s channel_ready, however, nodes[0] will generate its
3943         // announcement_signatures.
3944         nodes[0].node.handle_channel_ready(&nodes[1].node.get_our_node_id(), &bs_channel_ready);
3945         let events_6 = nodes[0].node.get_and_clear_pending_msg_events();
3946         assert_eq!(events_6.len(), 1);
3947         let as_announcement_sigs = match events_6[0] {
3948                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3949                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3950                         msg.clone()
3951                 },
3952                 _ => panic!("Unexpected event {:?}", events_6[0]),
3953         };
3954
3955         // When we deliver nodes[1]'s announcement_signatures to nodes[0], nodes[0] should immediately
3956         // broadcast the channel announcement globally, as well as re-send its (now-public)
3957         // channel_update.
3958         nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3959         let events_7 = nodes[0].node.get_and_clear_pending_msg_events();
3960         assert_eq!(events_7.len(), 1);
3961         let (chan_announcement, as_update) = match events_7[0] {
3962                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3963                         (msg.clone(), update_msg.clone())
3964                 },
3965                 _ => panic!("Unexpected event {:?}", events_7[0]),
3966         };
3967
3968         // Finally, deliver nodes[0]'s announcement_signatures to nodes[1] and make sure it creates the
3969         // same channel_announcement.
3970         nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3971         let events_8 = nodes[1].node.get_and_clear_pending_msg_events();
3972         assert_eq!(events_8.len(), 1);
3973         let bs_update = match events_8[0] {
3974                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3975                         assert_eq!(*msg, chan_announcement);
3976                         update_msg.clone()
3977                 },
3978                 _ => panic!("Unexpected event {:?}", events_8[0]),
3979         };
3980
3981         // Provide the channel announcement and public updates to the network graph
3982         nodes[0].gossip_sync.handle_channel_announcement(&chan_announcement).unwrap();
3983         nodes[0].gossip_sync.handle_channel_update(&bs_update).unwrap();
3984         nodes[0].gossip_sync.handle_channel_update(&as_update).unwrap();
3985
3986         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3987         let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3988         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
3989
3990         // Check that after deserialization and reconnection we can still generate an identical
3991         // channel_announcement from the cached signatures.
3992         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3993
3994         let nodes_0_serialized = nodes[0].node.encode();
3995         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
3996         get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
3997
3998         persister = test_utils::TestPersister::new();
3999         let keys_manager = &chanmon_cfgs[0].keys_manager;
4000         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);
4001         nodes[0].chain_monitor = &new_chain_monitor;
4002         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4003         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4004                 &mut chan_0_monitor_read, keys_manager).unwrap();
4005         assert!(chan_0_monitor_read.is_empty());
4006
4007         let mut nodes_0_read = &nodes_0_serialized[..];
4008         let (_, nodes_0_deserialized_tmp) = {
4009                 let mut channel_monitors = HashMap::new();
4010                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4011                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4012                         default_config: UserConfig::default(),
4013                         keys_manager,
4014                         fee_estimator: node_cfgs[0].fee_estimator,
4015                         chain_monitor: nodes[0].chain_monitor,
4016                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4017                         logger: nodes[0].logger,
4018                         channel_monitors,
4019                 }).unwrap()
4020         };
4021         nodes_0_deserialized = nodes_0_deserialized_tmp;
4022         assert!(nodes_0_read.is_empty());
4023
4024         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4025         nodes[0].node = &nodes_0_deserialized;
4026         check_added_monitors!(nodes[0], 1);
4027
4028         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4029 }
4030
4031 #[test]
4032 fn test_channel_ready_without_best_block_updated() {
4033         // Previously, if we were offline when a funding transaction was locked in, and then we came
4034         // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
4035         // generate a channel_ready until a later best_block_updated. This tests that we generate the
4036         // channel_ready immediately instead.
4037         let chanmon_cfgs = create_chanmon_cfgs(2);
4038         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4039         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4040         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4041         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
4042
4043         let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4044
4045         let conf_height = nodes[0].best_block_info().1 + 1;
4046         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
4047         let block_txn = [funding_tx];
4048         let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
4049         let conf_block_header = nodes[0].get_block_header(conf_height);
4050         nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
4051
4052         // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
4053         let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
4054         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
4055 }
4056
4057 #[test]
4058 fn test_drop_messages_peer_disconnect_dual_htlc() {
4059         // Test that we can handle reconnecting when both sides of a channel have pending
4060         // commitment_updates when we disconnect.
4061         let chanmon_cfgs = create_chanmon_cfgs(2);
4062         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4063         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4064         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4065         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4066
4067         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
4068
4069         // Now try to send a second payment which will fail to send
4070         let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
4071         nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
4072         check_added_monitors!(nodes[0], 1);
4073
4074         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
4075         assert_eq!(events_1.len(), 1);
4076         match events_1[0] {
4077                 MessageSendEvent::UpdateHTLCs { .. } => {},
4078                 _ => panic!("Unexpected event"),
4079         }
4080
4081         nodes[1].node.claim_funds(payment_preimage_1);
4082         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
4083         check_added_monitors!(nodes[1], 1);
4084
4085         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
4086         assert_eq!(events_2.len(), 1);
4087         match events_2[0] {
4088                 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 } } => {
4089                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
4090                         assert!(update_add_htlcs.is_empty());
4091                         assert_eq!(update_fulfill_htlcs.len(), 1);
4092                         assert!(update_fail_htlcs.is_empty());
4093                         assert!(update_fail_malformed_htlcs.is_empty());
4094                         assert!(update_fee.is_none());
4095
4096                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
4097                         let events_3 = nodes[0].node.get_and_clear_pending_events();
4098                         assert_eq!(events_3.len(), 1);
4099                         match events_3[0] {
4100                                 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4101                                         assert_eq!(*payment_preimage, payment_preimage_1);
4102                                         assert_eq!(*payment_hash, payment_hash_1);
4103                                 },
4104                                 _ => panic!("Unexpected event"),
4105                         }
4106
4107                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
4108                         let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4109                         // No commitment_signed so get_event_msg's assert(len == 1) passes
4110                         check_added_monitors!(nodes[0], 1);
4111                 },
4112                 _ => panic!("Unexpected event"),
4113         }
4114
4115         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
4116         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4117
4118         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
4119         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4120         assert_eq!(reestablish_1.len(), 1);
4121         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
4122         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4123         assert_eq!(reestablish_2.len(), 1);
4124
4125         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4126         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4127         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4128         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4129
4130         assert!(as_resp.0.is_none());
4131         assert!(bs_resp.0.is_none());
4132
4133         assert!(bs_resp.1.is_none());
4134         assert!(bs_resp.2.is_none());
4135
4136         assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4137
4138         assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4139         assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4140         assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4141         assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4142         assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4143         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4144         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4145         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4146         // No commitment_signed so get_event_msg's assert(len == 1) passes
4147         check_added_monitors!(nodes[1], 1);
4148
4149         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4150         let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4151         assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4152         assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4153         assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4154         assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4155         assert!(bs_second_commitment_signed.update_fee.is_none());
4156         check_added_monitors!(nodes[1], 1);
4157
4158         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4159         let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4160         assert!(as_commitment_signed.update_add_htlcs.is_empty());
4161         assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4162         assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4163         assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4164         assert!(as_commitment_signed.update_fee.is_none());
4165         check_added_monitors!(nodes[0], 1);
4166
4167         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4168         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4169         // No commitment_signed so get_event_msg's assert(len == 1) passes
4170         check_added_monitors!(nodes[0], 1);
4171
4172         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4173         let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4174         // No commitment_signed so get_event_msg's assert(len == 1) passes
4175         check_added_monitors!(nodes[1], 1);
4176
4177         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4178         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4179         check_added_monitors!(nodes[1], 1);
4180
4181         expect_pending_htlcs_forwardable!(nodes[1]);
4182
4183         let events_5 = nodes[1].node.get_and_clear_pending_events();
4184         assert_eq!(events_5.len(), 1);
4185         match events_5[0] {
4186                 Event::PaymentReceived { ref payment_hash, ref purpose, .. } => {
4187                         assert_eq!(payment_hash_2, *payment_hash);
4188                         match &purpose {
4189                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4190                                         assert!(payment_preimage.is_none());
4191                                         assert_eq!(payment_secret_2, *payment_secret);
4192                                 },
4193                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
4194                         }
4195                 },
4196                 _ => panic!("Unexpected event"),
4197         }
4198
4199         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4200         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4201         check_added_monitors!(nodes[0], 1);
4202
4203         expect_payment_path_successful!(nodes[0]);
4204         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4205 }
4206
4207 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4208         // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4209         // to avoid our counterparty failing the channel.
4210         let chanmon_cfgs = create_chanmon_cfgs(2);
4211         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4212         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4213         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4214
4215         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4216
4217         let our_payment_hash = if send_partial_mpp {
4218                 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4219                 // Use the utility function send_payment_along_path to send the payment with MPP data which
4220                 // indicates there are more HTLCs coming.
4221                 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.
4222                 let payment_id = PaymentId([42; 32]);
4223                 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();
4224                 check_added_monitors!(nodes[0], 1);
4225                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4226                 assert_eq!(events.len(), 1);
4227                 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4228                 // hop should *not* yet generate any PaymentReceived event(s).
4229                 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4230                 our_payment_hash
4231         } else {
4232                 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4233         };
4234
4235         let mut block = Block {
4236                 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
4237                 txdata: vec![],
4238         };
4239         connect_block(&nodes[0], &block);
4240         connect_block(&nodes[1], &block);
4241         let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4242         for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4243                 block.header.prev_blockhash = block.block_hash();
4244                 connect_block(&nodes[0], &block);
4245                 connect_block(&nodes[1], &block);
4246         }
4247
4248         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
4249
4250         check_added_monitors!(nodes[1], 1);
4251         let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4252         assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4253         assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4254         assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4255         assert!(htlc_timeout_updates.update_fee.is_none());
4256
4257         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4258         commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4259         // 100_000 msat as u64, followed by the height at which we failed back above
4260         let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
4261         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(block_count - 1));
4262         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4263 }
4264
4265 #[test]
4266 fn test_htlc_timeout() {
4267         do_test_htlc_timeout(true);
4268         do_test_htlc_timeout(false);
4269 }
4270
4271 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4272         // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4273         let chanmon_cfgs = create_chanmon_cfgs(3);
4274         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4275         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4276         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4277         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4278         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4279
4280         // Make sure all nodes are at the same starting height
4281         connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4282         connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4283         connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4284
4285         // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4286         let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4287         {
4288                 nodes[1].node.send_payment(&route, first_payment_hash, &Some(first_payment_secret)).unwrap();
4289         }
4290         assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4291         check_added_monitors!(nodes[1], 1);
4292
4293         // Now attempt to route a second payment, which should be placed in the holding cell
4294         let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4295         let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4296         sending_node.node.send_payment(&route, second_payment_hash, &Some(second_payment_secret)).unwrap();
4297         if forwarded_htlc {
4298                 check_added_monitors!(nodes[0], 1);
4299                 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4300                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4301                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4302                 expect_pending_htlcs_forwardable!(nodes[1]);
4303         }
4304         check_added_monitors!(nodes[1], 0);
4305
4306         connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4307         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4308         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4309         connect_blocks(&nodes[1], 1);
4310
4311         if forwarded_htlc {
4312                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
4313                 check_added_monitors!(nodes[1], 1);
4314                 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4315                 assert_eq!(fail_commit.len(), 1);
4316                 match fail_commit[0] {
4317                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4318                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4319                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4320                         },
4321                         _ => unreachable!(),
4322                 }
4323                 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4324         } else {
4325                 let events = nodes[1].node.get_and_clear_pending_events();
4326                 assert_eq!(events.len(), 2);
4327                 if let Event::PaymentPathFailed { ref payment_hash, .. } = events[0] {
4328                         assert_eq!(*payment_hash, second_payment_hash);
4329                 } else { panic!("Unexpected event"); }
4330                 if let Event::PaymentFailed { ref payment_hash, .. } = events[1] {
4331                         assert_eq!(*payment_hash, second_payment_hash);
4332                 } else { panic!("Unexpected event"); }
4333         }
4334 }
4335
4336 #[test]
4337 fn test_holding_cell_htlc_add_timeouts() {
4338         do_test_holding_cell_htlc_add_timeouts(false);
4339         do_test_holding_cell_htlc_add_timeouts(true);
4340 }
4341
4342 #[test]
4343 fn test_no_txn_manager_serialize_deserialize() {
4344         let chanmon_cfgs = create_chanmon_cfgs(2);
4345         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4346         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4347         let logger: test_utils::TestLogger;
4348         let fee_estimator: test_utils::TestFeeEstimator;
4349         let persister: test_utils::TestPersister;
4350         let new_chain_monitor: test_utils::TestChainMonitor;
4351         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4352         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4353
4354         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4355
4356         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4357
4358         let nodes_0_serialized = nodes[0].node.encode();
4359         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4360         get_monitor!(nodes[0], OutPoint { txid: tx.txid(), index: 0 }.to_channel_id())
4361                 .write(&mut chan_0_monitor_serialized).unwrap();
4362
4363         logger = test_utils::TestLogger::new();
4364         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4365         persister = test_utils::TestPersister::new();
4366         let keys_manager = &chanmon_cfgs[0].keys_manager;
4367         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4368         nodes[0].chain_monitor = &new_chain_monitor;
4369         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4370         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4371                 &mut chan_0_monitor_read, keys_manager).unwrap();
4372         assert!(chan_0_monitor_read.is_empty());
4373
4374         let mut nodes_0_read = &nodes_0_serialized[..];
4375         let config = UserConfig::default();
4376         let (_, nodes_0_deserialized_tmp) = {
4377                 let mut channel_monitors = HashMap::new();
4378                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4379                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4380                         default_config: config,
4381                         keys_manager,
4382                         fee_estimator: &fee_estimator,
4383                         chain_monitor: nodes[0].chain_monitor,
4384                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4385                         logger: &logger,
4386                         channel_monitors,
4387                 }).unwrap()
4388         };
4389         nodes_0_deserialized = nodes_0_deserialized_tmp;
4390         assert!(nodes_0_read.is_empty());
4391
4392         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4393         nodes[0].node = &nodes_0_deserialized;
4394         assert_eq!(nodes[0].node.list_channels().len(), 1);
4395         check_added_monitors!(nodes[0], 1);
4396
4397         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
4398         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4399         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
4400         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4401
4402         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4403         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4404         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4405         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4406
4407         let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4408         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
4409         for node in nodes.iter() {
4410                 assert!(node.gossip_sync.handle_channel_announcement(&announcement).unwrap());
4411                 node.gossip_sync.handle_channel_update(&as_update).unwrap();
4412                 node.gossip_sync.handle_channel_update(&bs_update).unwrap();
4413         }
4414
4415         send_payment(&nodes[0], &[&nodes[1]], 1000000);
4416 }
4417
4418 #[test]
4419 fn test_manager_serialize_deserialize_events() {
4420         // This test makes sure the events field in ChannelManager survives de/serialization
4421         let chanmon_cfgs = create_chanmon_cfgs(2);
4422         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4423         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4424         let fee_estimator: test_utils::TestFeeEstimator;
4425         let persister: test_utils::TestPersister;
4426         let logger: test_utils::TestLogger;
4427         let new_chain_monitor: test_utils::TestChainMonitor;
4428         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4429         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4430
4431         // Start creating a channel, but stop right before broadcasting the funding transaction
4432         let channel_value = 100000;
4433         let push_msat = 10001;
4434         let a_flags = channelmanager::provided_init_features();
4435         let b_flags = channelmanager::provided_init_features();
4436         let node_a = nodes.remove(0);
4437         let node_b = nodes.remove(0);
4438         node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
4439         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()));
4440         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()));
4441
4442         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, &node_b.node.get_our_node_id(), channel_value, 42);
4443
4444         node_a.node.funding_transaction_generated(&temporary_channel_id, &node_b.node.get_our_node_id(), tx.clone()).unwrap();
4445         check_added_monitors!(node_a, 0);
4446
4447         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()));
4448         {
4449                 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
4450                 assert_eq!(added_monitors.len(), 1);
4451                 assert_eq!(added_monitors[0].0, funding_output);
4452                 added_monitors.clear();
4453         }
4454
4455         let bs_funding_signed = get_event_msg!(node_b, MessageSendEvent::SendFundingSigned, node_a.node.get_our_node_id());
4456         node_a.node.handle_funding_signed(&node_b.node.get_our_node_id(), &bs_funding_signed);
4457         {
4458                 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
4459                 assert_eq!(added_monitors.len(), 1);
4460                 assert_eq!(added_monitors[0].0, funding_output);
4461                 added_monitors.clear();
4462         }
4463         // Normally, this is where node_a would broadcast the funding transaction, but the test de/serializes first instead
4464
4465         nodes.push(node_a);
4466         nodes.push(node_b);
4467
4468         // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4469         let nodes_0_serialized = nodes[0].node.encode();
4470         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4471         get_monitor!(nodes[0], bs_funding_signed.channel_id).write(&mut chan_0_monitor_serialized).unwrap();
4472
4473         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4474         logger = test_utils::TestLogger::new();
4475         persister = test_utils::TestPersister::new();
4476         let keys_manager = &chanmon_cfgs[0].keys_manager;
4477         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4478         nodes[0].chain_monitor = &new_chain_monitor;
4479         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4480         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4481                 &mut chan_0_monitor_read, keys_manager).unwrap();
4482         assert!(chan_0_monitor_read.is_empty());
4483
4484         let mut nodes_0_read = &nodes_0_serialized[..];
4485         let config = UserConfig::default();
4486         let (_, nodes_0_deserialized_tmp) = {
4487                 let mut channel_monitors = HashMap::new();
4488                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4489                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4490                         default_config: config,
4491                         keys_manager,
4492                         fee_estimator: &fee_estimator,
4493                         chain_monitor: nodes[0].chain_monitor,
4494                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4495                         logger: &logger,
4496                         channel_monitors,
4497                 }).unwrap()
4498         };
4499         nodes_0_deserialized = nodes_0_deserialized_tmp;
4500         assert!(nodes_0_read.is_empty());
4501
4502         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4503
4504         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4505         nodes[0].node = &nodes_0_deserialized;
4506
4507         // After deserializing, make sure the funding_transaction is still held by the channel manager
4508         let events_4 = nodes[0].node.get_and_clear_pending_events();
4509         assert_eq!(events_4.len(), 0);
4510         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
4511         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
4512
4513         // Make sure the channel is functioning as though the de/serialization never happened
4514         assert_eq!(nodes[0].node.list_channels().len(), 1);
4515         check_added_monitors!(nodes[0], 1);
4516
4517         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
4518         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4519         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
4520         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4521
4522         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4523         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4524         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4525         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4526
4527         let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4528         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
4529         for node in nodes.iter() {
4530                 assert!(node.gossip_sync.handle_channel_announcement(&announcement).unwrap());
4531                 node.gossip_sync.handle_channel_update(&as_update).unwrap();
4532                 node.gossip_sync.handle_channel_update(&bs_update).unwrap();
4533         }
4534
4535         send_payment(&nodes[0], &[&nodes[1]], 1000000);
4536 }
4537
4538 #[test]
4539 fn test_simple_manager_serialize_deserialize() {
4540         let chanmon_cfgs = create_chanmon_cfgs(2);
4541         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4542         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4543         let logger: test_utils::TestLogger;
4544         let fee_estimator: test_utils::TestFeeEstimator;
4545         let persister: test_utils::TestPersister;
4546         let new_chain_monitor: test_utils::TestChainMonitor;
4547         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4548         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4549         let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
4550
4551         let (our_payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4552         let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4553
4554         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4555
4556         let nodes_0_serialized = nodes[0].node.encode();
4557         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4558         get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
4559
4560         logger = test_utils::TestLogger::new();
4561         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4562         persister = test_utils::TestPersister::new();
4563         let keys_manager = &chanmon_cfgs[0].keys_manager;
4564         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4565         nodes[0].chain_monitor = &new_chain_monitor;
4566         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4567         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4568                 &mut chan_0_monitor_read, keys_manager).unwrap();
4569         assert!(chan_0_monitor_read.is_empty());
4570
4571         let mut nodes_0_read = &nodes_0_serialized[..];
4572         let (_, nodes_0_deserialized_tmp) = {
4573                 let mut channel_monitors = HashMap::new();
4574                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4575                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4576                         default_config: UserConfig::default(),
4577                         keys_manager,
4578                         fee_estimator: &fee_estimator,
4579                         chain_monitor: nodes[0].chain_monitor,
4580                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4581                         logger: &logger,
4582                         channel_monitors,
4583                 }).unwrap()
4584         };
4585         nodes_0_deserialized = nodes_0_deserialized_tmp;
4586         assert!(nodes_0_read.is_empty());
4587
4588         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4589         nodes[0].node = &nodes_0_deserialized;
4590         check_added_monitors!(nodes[0], 1);
4591
4592         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4593
4594         fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4595         claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
4596 }
4597
4598 #[test]
4599 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4600         // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4601         let chanmon_cfgs = create_chanmon_cfgs(4);
4602         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4603         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4604         let logger: test_utils::TestLogger;
4605         let fee_estimator: test_utils::TestFeeEstimator;
4606         let persister: test_utils::TestPersister;
4607         let new_chain_monitor: test_utils::TestChainMonitor;
4608         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4609         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4610         let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
4611         let chan_id_2 = create_announced_chan_between_nodes(&nodes, 2, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
4612         let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4613
4614         let mut node_0_stale_monitors_serialized = Vec::new();
4615         for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4616                 let mut writer = test_utils::TestVecWriter(Vec::new());
4617                 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4618                 node_0_stale_monitors_serialized.push(writer.0);
4619         }
4620
4621         let (our_payment_preimage, _, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4622
4623         // Serialize the ChannelManager here, but the monitor we keep up-to-date
4624         let nodes_0_serialized = nodes[0].node.encode();
4625
4626         route_payment(&nodes[0], &[&nodes[3]], 1000000);
4627         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4628         nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4629         nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4630
4631         // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4632         // nodes[3])
4633         let mut node_0_monitors_serialized = Vec::new();
4634         for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4635                 let mut writer = test_utils::TestVecWriter(Vec::new());
4636                 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4637                 node_0_monitors_serialized.push(writer.0);
4638         }
4639
4640         logger = test_utils::TestLogger::new();
4641         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4642         persister = test_utils::TestPersister::new();
4643         let keys_manager = &chanmon_cfgs[0].keys_manager;
4644         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4645         nodes[0].chain_monitor = &new_chain_monitor;
4646
4647
4648         let mut node_0_stale_monitors = Vec::new();
4649         for serialized in node_0_stale_monitors_serialized.iter() {
4650                 let mut read = &serialized[..];
4651                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4652                 assert!(read.is_empty());
4653                 node_0_stale_monitors.push(monitor);
4654         }
4655
4656         let mut node_0_monitors = Vec::new();
4657         for serialized in node_0_monitors_serialized.iter() {
4658                 let mut read = &serialized[..];
4659                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4660                 assert!(read.is_empty());
4661                 node_0_monitors.push(monitor);
4662         }
4663
4664         let mut nodes_0_read = &nodes_0_serialized[..];
4665         if let Err(msgs::DecodeError::InvalidValue) =
4666                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4667                 default_config: UserConfig::default(),
4668                 keys_manager,
4669                 fee_estimator: &fee_estimator,
4670                 chain_monitor: nodes[0].chain_monitor,
4671                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4672                 logger: &logger,
4673                 channel_monitors: node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4674         }) { } else {
4675                 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4676         };
4677
4678         let mut nodes_0_read = &nodes_0_serialized[..];
4679         let (_, nodes_0_deserialized_tmp) =
4680                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4681                 default_config: UserConfig::default(),
4682                 keys_manager,
4683                 fee_estimator: &fee_estimator,
4684                 chain_monitor: nodes[0].chain_monitor,
4685                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4686                 logger: &logger,
4687                 channel_monitors: node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4688         }).unwrap();
4689         nodes_0_deserialized = nodes_0_deserialized_tmp;
4690         assert!(nodes_0_read.is_empty());
4691
4692         { // Channel close should result in a commitment tx
4693                 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4694                 assert_eq!(txn.len(), 1);
4695                 check_spends!(txn[0], funding_tx);
4696                 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4697         }
4698
4699         for monitor in node_0_monitors.drain(..) {
4700                 assert!(nodes[0].chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor).is_ok());
4701                 check_added_monitors!(nodes[0], 1);
4702         }
4703         nodes[0].node = &nodes_0_deserialized;
4704         check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
4705
4706         // nodes[1] and nodes[2] have no lost state with nodes[0]...
4707         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4708         reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4709         //... and we can even still claim the payment!
4710         claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage);
4711
4712         nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
4713         let reestablish = get_chan_reestablish_msgs!(nodes[3], nodes[0]).pop().unwrap();
4714         nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
4715         nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4716         let mut found_err = false;
4717         for msg_event in nodes[0].node.get_and_clear_pending_msg_events() {
4718                 if let MessageSendEvent::HandleError { ref action, .. } = msg_event {
4719                         match action {
4720                                 &ErrorAction::SendErrorMessage { ref msg } => {
4721                                         assert_eq!(msg.channel_id, channel_id);
4722                                         assert!(!found_err);
4723                                         found_err = true;
4724                                 },
4725                                 _ => panic!("Unexpected event!"),
4726                         }
4727                 }
4728         }
4729         assert!(found_err);
4730 }
4731
4732 macro_rules! check_spendable_outputs {
4733         ($node: expr, $keysinterface: expr) => {
4734                 {
4735                         let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4736                         let mut txn = Vec::new();
4737                         let mut all_outputs = Vec::new();
4738                         let secp_ctx = Secp256k1::new();
4739                         for event in events.drain(..) {
4740                                 match event {
4741                                         Event::SpendableOutputs { mut outputs } => {
4742                                                 for outp in outputs.drain(..) {
4743                                                         txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4744                                                         all_outputs.push(outp);
4745                                                 }
4746                                         },
4747                                         _ => panic!("Unexpected event"),
4748                                 };
4749                         }
4750                         if all_outputs.len() > 1 {
4751                                 if let Ok(tx) = $keysinterface.backing.spend_spendable_outputs(&all_outputs.iter().map(|a| a).collect::<Vec<_>>(), Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx) {
4752                                         txn.push(tx);
4753                                 }
4754                         }
4755                         txn
4756                 }
4757         }
4758 }
4759
4760 #[test]
4761 fn test_claim_sizeable_push_msat() {
4762         // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4763         let chanmon_cfgs = create_chanmon_cfgs(2);
4764         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4765         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4766         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4767
4768         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4769         nodes[1].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
4770         check_closed_broadcast!(nodes[1], true);
4771         check_added_monitors!(nodes[1], 1);
4772         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4773         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4774         assert_eq!(node_txn.len(), 1);
4775         check_spends!(node_txn[0], chan.3);
4776         assert_eq!(node_txn[0].output.len(), 2); // We can't force trimming of to_remote output as channel_reserve_satoshis block us to do so at channel opening
4777
4778         mine_transaction(&nodes[1], &node_txn[0]);
4779         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4780
4781         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4782         assert_eq!(spend_txn.len(), 1);
4783         assert_eq!(spend_txn[0].input.len(), 1);
4784         check_spends!(spend_txn[0], node_txn[0]);
4785         assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4786 }
4787
4788 #[test]
4789 fn test_claim_on_remote_sizeable_push_msat() {
4790         // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4791         // to_remote output is encumbered by a P2WPKH
4792         let chanmon_cfgs = create_chanmon_cfgs(2);
4793         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4794         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4795         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4796
4797         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4798         nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
4799         check_closed_broadcast!(nodes[0], true);
4800         check_added_monitors!(nodes[0], 1);
4801         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4802
4803         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4804         assert_eq!(node_txn.len(), 1);
4805         check_spends!(node_txn[0], chan.3);
4806         assert_eq!(node_txn[0].output.len(), 2); // We can't force trimming of to_remote output as channel_reserve_satoshis block us to do so at channel opening
4807
4808         mine_transaction(&nodes[1], &node_txn[0]);
4809         check_closed_broadcast!(nodes[1], true);
4810         check_added_monitors!(nodes[1], 1);
4811         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4812         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4813
4814         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4815         assert_eq!(spend_txn.len(), 1);
4816         check_spends!(spend_txn[0], node_txn[0]);
4817 }
4818
4819 #[test]
4820 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4821         // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4822         // to_remote output is encumbered by a P2WPKH
4823
4824         let chanmon_cfgs = create_chanmon_cfgs(2);
4825         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4826         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4827         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4828
4829         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4830         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4831         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4832         assert_eq!(revoked_local_txn[0].input.len(), 1);
4833         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4834
4835         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4836         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4837         check_closed_broadcast!(nodes[1], true);
4838         check_added_monitors!(nodes[1], 1);
4839         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4840
4841         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4842         mine_transaction(&nodes[1], &node_txn[0]);
4843         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4844
4845         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4846         assert_eq!(spend_txn.len(), 3);
4847         check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4848         check_spends!(spend_txn[1], node_txn[0]);
4849         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4850 }
4851
4852 #[test]
4853 fn test_static_spendable_outputs_preimage_tx() {
4854         let chanmon_cfgs = create_chanmon_cfgs(2);
4855         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4856         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4857         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4858
4859         // Create some initial channels
4860         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4861
4862         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
4863
4864         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4865         assert_eq!(commitment_tx[0].input.len(), 1);
4866         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4867
4868         // Settle A's commitment tx on B's chain
4869         nodes[1].node.claim_funds(payment_preimage);
4870         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
4871         check_added_monitors!(nodes[1], 1);
4872         mine_transaction(&nodes[1], &commitment_tx[0]);
4873         check_added_monitors!(nodes[1], 1);
4874         let events = nodes[1].node.get_and_clear_pending_msg_events();
4875         match events[0] {
4876                 MessageSendEvent::UpdateHTLCs { .. } => {},
4877                 _ => panic!("Unexpected event"),
4878         }
4879         match events[1] {
4880                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4881                 _ => panic!("Unexepected event"),
4882         }
4883
4884         // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4885         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4886         assert_eq!(node_txn.len(), 3);
4887         check_spends!(node_txn[0], commitment_tx[0]);
4888         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4889         check_spends!(node_txn[1], chan_1.3);
4890         check_spends!(node_txn[2], node_txn[1]);
4891
4892         mine_transaction(&nodes[1], &node_txn[0]);
4893         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4894         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4895
4896         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4897         assert_eq!(spend_txn.len(), 1);
4898         check_spends!(spend_txn[0], node_txn[0]);
4899 }
4900
4901 #[test]
4902 fn test_static_spendable_outputs_timeout_tx() {
4903         let chanmon_cfgs = create_chanmon_cfgs(2);
4904         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4905         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4906         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4907
4908         // Create some initial channels
4909         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4910
4911         // Rebalance the network a bit by relaying one payment through all the channels ...
4912         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4913
4914         let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4915
4916         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4917         assert_eq!(commitment_tx[0].input.len(), 1);
4918         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4919
4920         // Settle A's commitment tx on B' chain
4921         mine_transaction(&nodes[1], &commitment_tx[0]);
4922         check_added_monitors!(nodes[1], 1);
4923         let events = nodes[1].node.get_and_clear_pending_msg_events();
4924         match events[0] {
4925                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4926                 _ => panic!("Unexpected event"),
4927         }
4928         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4929
4930         // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4931         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4932         assert_eq!(node_txn.len(), 2); // ChannelManager : 1 local commitent tx, ChannelMonitor: timeout tx
4933         check_spends!(node_txn[0], chan_1.3.clone());
4934         check_spends!(node_txn[1],  commitment_tx[0].clone());
4935         assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4936
4937         mine_transaction(&nodes[1], &node_txn[1]);
4938         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4939         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4940         expect_payment_failed!(nodes[1], our_payment_hash, false);
4941
4942         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4943         assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4944         check_spends!(spend_txn[0], commitment_tx[0]);
4945         check_spends!(spend_txn[1], node_txn[1]);
4946         check_spends!(spend_txn[2], node_txn[1], commitment_tx[0]); // All outputs
4947 }
4948
4949 #[test]
4950 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4951         let chanmon_cfgs = create_chanmon_cfgs(2);
4952         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4953         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4954         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4955
4956         // Create some initial channels
4957         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4958
4959         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4960         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4961         assert_eq!(revoked_local_txn[0].input.len(), 1);
4962         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4963
4964         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4965
4966         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4967         check_closed_broadcast!(nodes[1], true);
4968         check_added_monitors!(nodes[1], 1);
4969         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4970
4971         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4972         assert_eq!(node_txn.len(), 2);
4973         assert_eq!(node_txn[0].input.len(), 2);
4974         check_spends!(node_txn[0], revoked_local_txn[0]);
4975
4976         mine_transaction(&nodes[1], &node_txn[0]);
4977         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4978
4979         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4980         assert_eq!(spend_txn.len(), 1);
4981         check_spends!(spend_txn[0], node_txn[0]);
4982 }
4983
4984 #[test]
4985 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4986         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4987         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4988         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4989         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4990         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4991
4992         // Create some initial channels
4993         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4994
4995         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4996         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4997         assert_eq!(revoked_local_txn[0].input.len(), 1);
4998         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4999
5000         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
5001
5002         // A will generate HTLC-Timeout from revoked commitment tx
5003         mine_transaction(&nodes[0], &revoked_local_txn[0]);
5004         check_closed_broadcast!(nodes[0], true);
5005         check_added_monitors!(nodes[0], 1);
5006         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5007         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5008
5009         let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
5010         assert_eq!(revoked_htlc_txn.len(), 2);
5011         check_spends!(revoked_htlc_txn[0], chan_1.3);
5012         assert_eq!(revoked_htlc_txn[1].input.len(), 1);
5013         assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5014         check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
5015         assert_ne!(revoked_htlc_txn[1].lock_time.0, 0); // HTLC-Timeout
5016
5017         // B will generate justice tx from A's revoked commitment/HTLC tx
5018         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
5019         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[1].clone()] });
5020         check_closed_broadcast!(nodes[1], true);
5021         check_added_monitors!(nodes[1], 1);
5022         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5023
5024         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5025         assert_eq!(node_txn.len(), 3); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs, ChannelManager: local commitment tx
5026         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5027         // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
5028         // transactions next...
5029         assert_eq!(node_txn[0].input.len(), 3);
5030         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[1]);
5031
5032         assert_eq!(node_txn[1].input.len(), 2);
5033         check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[1]);
5034         if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[1].txid() {
5035                 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
5036         } else {
5037                 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[1].txid());
5038                 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[1].input[0].previous_output);
5039         }
5040
5041         assert_eq!(node_txn[2].input.len(), 1);
5042         check_spends!(node_txn[2], chan_1.3);
5043
5044         mine_transaction(&nodes[1], &node_txn[1]);
5045         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5046
5047         // Check B's ChannelMonitor was able to generate the right spendable output descriptor
5048         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5049         assert_eq!(spend_txn.len(), 1);
5050         assert_eq!(spend_txn[0].input.len(), 1);
5051         check_spends!(spend_txn[0], node_txn[1]);
5052 }
5053
5054 #[test]
5055 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
5056         let mut chanmon_cfgs = create_chanmon_cfgs(2);
5057         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
5058         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5059         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5060         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5061
5062         // Create some initial channels
5063         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5064
5065         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5066         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5067         assert_eq!(revoked_local_txn[0].input.len(), 1);
5068         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5069
5070         // The to-be-revoked commitment tx should have one HTLC and one to_remote output
5071         assert_eq!(revoked_local_txn[0].output.len(), 2);
5072
5073         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
5074
5075         // B will generate HTLC-Success from revoked commitment tx
5076         mine_transaction(&nodes[1], &revoked_local_txn[0]);
5077         check_closed_broadcast!(nodes[1], true);
5078         check_added_monitors!(nodes[1], 1);
5079         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5080         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5081
5082         assert_eq!(revoked_htlc_txn.len(), 2);
5083         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
5084         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5085         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
5086
5087         // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
5088         let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
5089         assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
5090
5091         // A will generate justice tx from B's revoked commitment/HTLC tx
5092         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
5093         connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
5094         check_closed_broadcast!(nodes[0], true);
5095         check_added_monitors!(nodes[0], 1);
5096         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5097
5098         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5099         assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
5100
5101         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5102         // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
5103         // transactions next...
5104         assert_eq!(node_txn[0].input.len(), 2);
5105         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
5106         if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
5107                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5108         } else {
5109                 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
5110                 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5111         }
5112
5113         assert_eq!(node_txn[1].input.len(), 1);
5114         check_spends!(node_txn[1], revoked_htlc_txn[0]);
5115
5116         check_spends!(node_txn[2], chan_1.3);
5117
5118         mine_transaction(&nodes[0], &node_txn[1]);
5119         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5120
5121         // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
5122         // didn't try to generate any new transactions.
5123
5124         // Check A's ChannelMonitor was able to generate the right spendable output descriptor
5125         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5126         assert_eq!(spend_txn.len(), 3);
5127         assert_eq!(spend_txn[0].input.len(), 1);
5128         check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
5129         assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5130         check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
5131         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
5132 }
5133
5134 #[test]
5135 fn test_onchain_to_onchain_claim() {
5136         // Test that in case of channel closure, we detect the state of output and claim HTLC
5137         // on downstream peer's remote commitment tx.
5138         // First, have C claim an HTLC against its own latest commitment transaction.
5139         // Then, broadcast these to B, which should update the monitor downstream on the A<->B
5140         // channel.
5141         // Finally, check that B will claim the HTLC output if A's latest commitment transaction
5142         // gets broadcast.
5143
5144         let chanmon_cfgs = create_chanmon_cfgs(3);
5145         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5146         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5147         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5148
5149         // Create some initial channels
5150         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5151         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5152
5153         // Ensure all nodes are at the same height
5154         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5155         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5156         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5157         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5158
5159         // Rebalance the network a bit by relaying one payment through all the channels ...
5160         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5161         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5162
5163         let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
5164         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
5165         check_spends!(commitment_tx[0], chan_2.3);
5166         nodes[2].node.claim_funds(payment_preimage);
5167         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
5168         check_added_monitors!(nodes[2], 1);
5169         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5170         assert!(updates.update_add_htlcs.is_empty());
5171         assert!(updates.update_fail_htlcs.is_empty());
5172         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5173         assert!(updates.update_fail_malformed_htlcs.is_empty());
5174
5175         mine_transaction(&nodes[2], &commitment_tx[0]);
5176         check_closed_broadcast!(nodes[2], true);
5177         check_added_monitors!(nodes[2], 1);
5178         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5179
5180         let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
5181         assert_eq!(c_txn.len(), 3);
5182         assert_eq!(c_txn[0], c_txn[2]);
5183         assert_eq!(commitment_tx[0], c_txn[1]);
5184         check_spends!(c_txn[1], chan_2.3);
5185         check_spends!(c_txn[2], c_txn[1]);
5186         assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
5187         assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5188         assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5189         assert_eq!(c_txn[0].lock_time.0, 0); // Success tx
5190
5191         // 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
5192         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
5193         connect_block(&nodes[1], &Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]});
5194         check_added_monitors!(nodes[1], 1);
5195         let events = nodes[1].node.get_and_clear_pending_events();
5196         assert_eq!(events.len(), 2);
5197         match events[0] {
5198                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5199                 _ => panic!("Unexpected event"),
5200         }
5201         match events[1] {
5202                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
5203                         assert_eq!(fee_earned_msat, Some(1000));
5204                         assert_eq!(prev_channel_id, Some(chan_1.2));
5205                         assert_eq!(claim_from_onchain_tx, true);
5206                         assert_eq!(next_channel_id, Some(chan_2.2));
5207                 },
5208                 _ => panic!("Unexpected event"),
5209         }
5210         {
5211                 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5212                 // ChannelMonitor: claim tx
5213                 assert_eq!(b_txn.len(), 1);
5214                 check_spends!(b_txn[0], chan_2.3); // B local commitment tx, issued by ChannelManager
5215                 b_txn.clear();
5216         }
5217         check_added_monitors!(nodes[1], 1);
5218         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5219         assert_eq!(msg_events.len(), 3);
5220         match msg_events[0] {
5221                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5222                 _ => panic!("Unexpected event"),
5223         }
5224         match msg_events[1] {
5225                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
5226                 _ => panic!("Unexpected event"),
5227         }
5228         match msg_events[2] {
5229                 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, .. } } => {
5230                         assert!(update_add_htlcs.is_empty());
5231                         assert!(update_fail_htlcs.is_empty());
5232                         assert_eq!(update_fulfill_htlcs.len(), 1);
5233                         assert!(update_fail_malformed_htlcs.is_empty());
5234                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5235                 },
5236                 _ => panic!("Unexpected event"),
5237         };
5238         // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
5239         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5240         mine_transaction(&nodes[1], &commitment_tx[0]);
5241         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5242         let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5243         // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
5244         assert_eq!(b_txn.len(), 3);
5245         check_spends!(b_txn[1], chan_1.3);
5246         check_spends!(b_txn[2], b_txn[1]);
5247         check_spends!(b_txn[0], commitment_tx[0]);
5248         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5249         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5250         assert_eq!(b_txn[0].lock_time.0, 0); // Success tx
5251
5252         check_closed_broadcast!(nodes[1], true);
5253         check_added_monitors!(nodes[1], 1);
5254 }
5255
5256 #[test]
5257 fn test_duplicate_payment_hash_one_failure_one_success() {
5258         // Topology : A --> B --> C --> D
5259         // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5260         // Note that because C will refuse to generate two payment secrets for the same payment hash,
5261         // we forward one of the payments onwards to D.
5262         let chanmon_cfgs = create_chanmon_cfgs(4);
5263         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
5264         // When this test was written, the default base fee floated based on the HTLC count.
5265         // It is now fixed, so we simply set the fee to the expected value here.
5266         let mut config = test_default_channel_config();
5267         config.channel_config.forwarding_fee_base_msat = 196;
5268         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
5269                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5270         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
5271
5272         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5273         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5274         create_announced_chan_between_nodes(&nodes, 2, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5275
5276         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5277         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5278         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5279         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5280         connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
5281
5282         let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 900_000);
5283
5284         let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200).unwrap();
5285         // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
5286         // script push size limit so that the below script length checks match
5287         // ACCEPTED_HTLC_SCRIPT_WEIGHT.
5288         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id())
5289                 .with_features(channelmanager::provided_invoice_features());
5290         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 900000, TEST_FINAL_CLTV - 40);
5291         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 900000, duplicate_payment_hash, payment_secret);
5292
5293         let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5294         assert_eq!(commitment_txn[0].input.len(), 1);
5295         check_spends!(commitment_txn[0], chan_2.3);
5296
5297         mine_transaction(&nodes[1], &commitment_txn[0]);
5298         check_closed_broadcast!(nodes[1], true);
5299         check_added_monitors!(nodes[1], 1);
5300         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5301         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
5302
5303         let htlc_timeout_tx;
5304         { // Extract one of the two HTLC-Timeout transaction
5305                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5306                 // ChannelMonitor: timeout tx * 2-or-3, ChannelManager: local commitment tx
5307                 assert!(node_txn.len() == 4 || node_txn.len() == 3);
5308                 check_spends!(node_txn[0], chan_2.3);
5309
5310                 check_spends!(node_txn[1], commitment_txn[0]);
5311                 assert_eq!(node_txn[1].input.len(), 1);
5312
5313                 if node_txn.len() > 3 {
5314                         check_spends!(node_txn[2], commitment_txn[0]);
5315                         assert_eq!(node_txn[2].input.len(), 1);
5316                         assert_eq!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
5317
5318                         check_spends!(node_txn[3], commitment_txn[0]);
5319                         assert_ne!(node_txn[1].input[0].previous_output, node_txn[3].input[0].previous_output);
5320                 } else {
5321                         check_spends!(node_txn[2], commitment_txn[0]);
5322                         assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
5323                 }
5324
5325                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5326                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5327                 if node_txn.len() > 3 {
5328                         assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5329                 }
5330                 htlc_timeout_tx = node_txn[1].clone();
5331         }
5332
5333         nodes[2].node.claim_funds(our_payment_preimage);
5334         expect_payment_claimed!(nodes[2], duplicate_payment_hash, 900_000);
5335
5336         mine_transaction(&nodes[2], &commitment_txn[0]);
5337         check_added_monitors!(nodes[2], 2);
5338         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5339         let events = nodes[2].node.get_and_clear_pending_msg_events();
5340         match events[0] {
5341                 MessageSendEvent::UpdateHTLCs { .. } => {},
5342                 _ => panic!("Unexpected event"),
5343         }
5344         match events[1] {
5345                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5346                 _ => panic!("Unexepected event"),
5347         }
5348         let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5349         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)
5350         check_spends!(htlc_success_txn[0], commitment_txn[0]);
5351         check_spends!(htlc_success_txn[1], commitment_txn[0]);
5352         assert_eq!(htlc_success_txn[0].input.len(), 1);
5353         assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5354         assert_eq!(htlc_success_txn[1].input.len(), 1);
5355         assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5356         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
5357         assert_eq!(htlc_success_txn[2], commitment_txn[0]);
5358         assert_eq!(htlc_success_txn[3], htlc_success_txn[0]);
5359         assert_eq!(htlc_success_txn[4], htlc_success_txn[1]);
5360         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
5361
5362         mine_transaction(&nodes[1], &htlc_timeout_tx);
5363         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5364         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
5365         let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5366         assert!(htlc_updates.update_add_htlcs.is_empty());
5367         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5368         let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
5369         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5370         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5371         check_added_monitors!(nodes[1], 1);
5372
5373         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5374         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5375         {
5376                 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5377         }
5378         expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
5379
5380         // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5381         // Note that the fee paid is effectively double as the HTLC value (including the nodes[1] fee
5382         // and nodes[2] fee) is rounded down and then claimed in full.
5383         mine_transaction(&nodes[1], &htlc_success_txn[0]);
5384         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196*2), true, true);
5385         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5386         assert!(updates.update_add_htlcs.is_empty());
5387         assert!(updates.update_fail_htlcs.is_empty());
5388         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5389         assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
5390         assert!(updates.update_fail_malformed_htlcs.is_empty());
5391         check_added_monitors!(nodes[1], 1);
5392
5393         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5394         commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5395
5396         let events = nodes[0].node.get_and_clear_pending_events();
5397         match events[0] {
5398                 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
5399                         assert_eq!(*payment_preimage, our_payment_preimage);
5400                         assert_eq!(*payment_hash, duplicate_payment_hash);
5401                 }
5402                 _ => panic!("Unexpected event"),
5403         }
5404 }
5405
5406 #[test]
5407 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5408         let chanmon_cfgs = create_chanmon_cfgs(2);
5409         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5410         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5411         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5412
5413         // Create some initial channels
5414         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5415
5416         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
5417         let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5418         assert_eq!(local_txn.len(), 1);
5419         assert_eq!(local_txn[0].input.len(), 1);
5420         check_spends!(local_txn[0], chan_1.3);
5421
5422         // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5423         nodes[1].node.claim_funds(payment_preimage);
5424         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
5425         check_added_monitors!(nodes[1], 1);
5426
5427         mine_transaction(&nodes[1], &local_txn[0]);
5428         check_added_monitors!(nodes[1], 1);
5429         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5430         let events = nodes[1].node.get_and_clear_pending_msg_events();
5431         match events[0] {
5432                 MessageSendEvent::UpdateHTLCs { .. } => {},
5433                 _ => panic!("Unexpected event"),
5434         }
5435         match events[1] {
5436                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5437                 _ => panic!("Unexepected event"),
5438         }
5439         let node_tx = {
5440                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5441                 assert_eq!(node_txn.len(), 3);
5442                 assert_eq!(node_txn[0], node_txn[2]);
5443                 assert_eq!(node_txn[1], local_txn[0]);
5444                 assert_eq!(node_txn[0].input.len(), 1);
5445                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5446                 check_spends!(node_txn[0], local_txn[0]);
5447                 node_txn[0].clone()
5448         };
5449
5450         mine_transaction(&nodes[1], &node_tx);
5451         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
5452
5453         // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5454         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5455         assert_eq!(spend_txn.len(), 1);
5456         assert_eq!(spend_txn[0].input.len(), 1);
5457         check_spends!(spend_txn[0], node_tx);
5458         assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5459 }
5460
5461 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5462         // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5463         // unrevoked commitment transaction.
5464         // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5465         // a remote RAA before they could be failed backwards (and combinations thereof).
5466         // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5467         // use the same payment hashes.
5468         // Thus, we use a six-node network:
5469         //
5470         // A \         / E
5471         //    - C - D -
5472         // B /         \ F
5473         // And test where C fails back to A/B when D announces its latest commitment transaction
5474         let chanmon_cfgs = create_chanmon_cfgs(6);
5475         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5476         // When this test was written, the default base fee floated based on the HTLC count.
5477         // It is now fixed, so we simply set the fee to the expected value here.
5478         let mut config = test_default_channel_config();
5479         config.channel_config.forwarding_fee_base_msat = 196;
5480         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
5481                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5482         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5483
5484         let _chan_0_2 = create_announced_chan_between_nodes(&nodes, 0, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5485         let _chan_1_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5486         let chan_2_3 = create_announced_chan_between_nodes(&nodes, 2, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5487         let chan_3_4 = create_announced_chan_between_nodes(&nodes, 3, 4, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5488         let chan_3_5  = create_announced_chan_between_nodes(&nodes, 3, 5, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5489
5490         // Rebalance and check output sanity...
5491         send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
5492         send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
5493         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 2);
5494
5495         let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan_2_3.2).unwrap().holder_dust_limit_satoshis;
5496         // 0th HTLC:
5497         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
5498         // 1st HTLC:
5499         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
5500         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5501         // 2nd HTLC:
5502         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
5503         // 3rd HTLC:
5504         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
5505         // 4th HTLC:
5506         let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5507         // 5th HTLC:
5508         let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5509         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5510         // 6th HTLC:
5511         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());
5512         // 7th HTLC:
5513         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());
5514
5515         // 8th HTLC:
5516         let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5517         // 9th HTLC:
5518         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5519         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
5520
5521         // 10th HTLC:
5522         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
5523         // 11th HTLC:
5524         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5525         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());
5526
5527         // Double-check that six of the new HTLC were added
5528         // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5529         // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5530         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2).len(), 1);
5531         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 8);
5532
5533         // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5534         // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5535         nodes[4].node.fail_htlc_backwards(&payment_hash_1);
5536         nodes[4].node.fail_htlc_backwards(&payment_hash_3);
5537         nodes[4].node.fail_htlc_backwards(&payment_hash_5);
5538         nodes[4].node.fail_htlc_backwards(&payment_hash_6);
5539         check_added_monitors!(nodes[4], 0);
5540
5541         let failed_destinations = vec![
5542                 HTLCDestination::FailedPayment { payment_hash: payment_hash_1 },
5543                 HTLCDestination::FailedPayment { payment_hash: payment_hash_3 },
5544                 HTLCDestination::FailedPayment { payment_hash: payment_hash_5 },
5545                 HTLCDestination::FailedPayment { payment_hash: payment_hash_6 },
5546         ];
5547         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[4], failed_destinations);
5548         check_added_monitors!(nodes[4], 1);
5549
5550         let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5551         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5552         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5553         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5554         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5555         commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5556
5557         // Fail 3rd below-dust and 7th above-dust HTLCs
5558         nodes[5].node.fail_htlc_backwards(&payment_hash_2);
5559         nodes[5].node.fail_htlc_backwards(&payment_hash_4);
5560         check_added_monitors!(nodes[5], 0);
5561
5562         let failed_destinations_2 = vec![
5563                 HTLCDestination::FailedPayment { payment_hash: payment_hash_2 },
5564                 HTLCDestination::FailedPayment { payment_hash: payment_hash_4 },
5565         ];
5566         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[5], failed_destinations_2);
5567         check_added_monitors!(nodes[5], 1);
5568
5569         let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5570         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5571         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5572         commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5573
5574         let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5575
5576         // After 4 and 2 removes respectively above in nodes[4] and nodes[5], nodes[3] should receive 6 PaymentForwardedFailed events
5577         let failed_destinations_3 = vec![
5578                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5579                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5580                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5581                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5582                 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5583                 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5584         ];
5585         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations_3);
5586         check_added_monitors!(nodes[3], 1);
5587         let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5588         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5589         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5590         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5591         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5592         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5593         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5594         if deliver_last_raa {
5595                 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5596         } else {
5597                 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5598         }
5599
5600         // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5601         // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5602         // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5603         // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5604         //
5605         // We now broadcast the latest commitment transaction, which *should* result in failures for
5606         // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5607         // the non-broadcast above-dust HTLCs.
5608         //
5609         // Alternatively, we may broadcast the previous commitment transaction, which should only
5610         // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5611         let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5612
5613         if announce_latest {
5614                 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5615         } else {
5616                 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5617         }
5618         let events = nodes[2].node.get_and_clear_pending_events();
5619         let close_event = if deliver_last_raa {
5620                 assert_eq!(events.len(), 2 + 6);
5621                 events.last().clone().unwrap()
5622         } else {
5623                 assert_eq!(events.len(), 1);
5624                 events.last().clone().unwrap()
5625         };
5626         match close_event {
5627                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5628                 _ => panic!("Unexpected event"),
5629         }
5630
5631         connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5632         check_closed_broadcast!(nodes[2], true);
5633         if deliver_last_raa {
5634                 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5635
5636                 let expected_destinations: Vec<HTLCDestination> = repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(3).collect();
5637                 expect_htlc_handling_failed_destinations!(nodes[2].node.get_and_clear_pending_events(), expected_destinations);
5638         } else {
5639                 let expected_destinations: Vec<HTLCDestination> = if announce_latest {
5640                         repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(9).collect()
5641                 } else {
5642                         repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(6).collect()
5643                 };
5644
5645                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], expected_destinations);
5646         }
5647         check_added_monitors!(nodes[2], 3);
5648
5649         let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5650         assert_eq!(cs_msgs.len(), 2);
5651         let mut a_done = false;
5652         for msg in cs_msgs {
5653                 match msg {
5654                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5655                                 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5656                                 // should be failed-backwards here.
5657                                 let target = if *node_id == nodes[0].node.get_our_node_id() {
5658                                         // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5659                                         for htlc in &updates.update_fail_htlcs {
5660                                                 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 });
5661                                         }
5662                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5663                                         assert!(!a_done);
5664                                         a_done = true;
5665                                         &nodes[0]
5666                                 } else {
5667                                         // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5668                                         for htlc in &updates.update_fail_htlcs {
5669                                                 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5670                                         }
5671                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5672                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5673                                         &nodes[1]
5674                                 };
5675                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5676                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5677                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5678                                 if announce_latest {
5679                                         target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5680                                         if *node_id == nodes[0].node.get_our_node_id() {
5681                                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5682                                         }
5683                                 }
5684                                 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5685                         },
5686                         _ => panic!("Unexpected event"),
5687                 }
5688         }
5689
5690         let as_events = nodes[0].node.get_and_clear_pending_events();
5691         assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5692         let mut as_failds = HashSet::new();
5693         let mut as_updates = 0;
5694         for event in as_events.iter() {
5695                 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref network_update, .. } = event {
5696                         assert!(as_failds.insert(*payment_hash));
5697                         if *payment_hash != payment_hash_2 {
5698                                 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5699                         } else {
5700                                 assert!(!payment_failed_permanently);
5701                         }
5702                         if network_update.is_some() {
5703                                 as_updates += 1;
5704                         }
5705                 } else { panic!("Unexpected event"); }
5706         }
5707         assert!(as_failds.contains(&payment_hash_1));
5708         assert!(as_failds.contains(&payment_hash_2));
5709         if announce_latest {
5710                 assert!(as_failds.contains(&payment_hash_3));
5711                 assert!(as_failds.contains(&payment_hash_5));
5712         }
5713         assert!(as_failds.contains(&payment_hash_6));
5714
5715         let bs_events = nodes[1].node.get_and_clear_pending_events();
5716         assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5717         let mut bs_failds = HashSet::new();
5718         let mut bs_updates = 0;
5719         for event in bs_events.iter() {
5720                 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref network_update, .. } = event {
5721                         assert!(bs_failds.insert(*payment_hash));
5722                         if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5723                                 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5724                         } else {
5725                                 assert!(!payment_failed_permanently);
5726                         }
5727                         if network_update.is_some() {
5728                                 bs_updates += 1;
5729                         }
5730                 } else { panic!("Unexpected event"); }
5731         }
5732         assert!(bs_failds.contains(&payment_hash_1));
5733         assert!(bs_failds.contains(&payment_hash_2));
5734         if announce_latest {
5735                 assert!(bs_failds.contains(&payment_hash_4));
5736         }
5737         assert!(bs_failds.contains(&payment_hash_5));
5738
5739         // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5740         // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5741         // unknown-preimage-etc, B should have gotten 2. Thus, in the
5742         // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5743         assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5744         assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5745 }
5746
5747 #[test]
5748 fn test_fail_backwards_latest_remote_announce_a() {
5749         do_test_fail_backwards_unrevoked_remote_announce(false, true);
5750 }
5751
5752 #[test]
5753 fn test_fail_backwards_latest_remote_announce_b() {
5754         do_test_fail_backwards_unrevoked_remote_announce(true, true);
5755 }
5756
5757 #[test]
5758 fn test_fail_backwards_previous_remote_announce() {
5759         do_test_fail_backwards_unrevoked_remote_announce(false, false);
5760         // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5761         // tested for in test_commitment_revoked_fail_backward_exhaustive()
5762 }
5763
5764 #[test]
5765 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5766         let chanmon_cfgs = create_chanmon_cfgs(2);
5767         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5768         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5769         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5770
5771         // Create some initial channels
5772         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5773
5774         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5775         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5776         assert_eq!(local_txn[0].input.len(), 1);
5777         check_spends!(local_txn[0], chan_1.3);
5778
5779         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5780         mine_transaction(&nodes[0], &local_txn[0]);
5781         check_closed_broadcast!(nodes[0], true);
5782         check_added_monitors!(nodes[0], 1);
5783         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5784         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5785
5786         let htlc_timeout = {
5787                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5788                 assert_eq!(node_txn.len(), 2);
5789                 check_spends!(node_txn[0], chan_1.3);
5790                 assert_eq!(node_txn[1].input.len(), 1);
5791                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5792                 check_spends!(node_txn[1], local_txn[0]);
5793                 node_txn[1].clone()
5794         };
5795
5796         mine_transaction(&nodes[0], &htlc_timeout);
5797         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5798         expect_payment_failed!(nodes[0], our_payment_hash, false);
5799
5800         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5801         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5802         assert_eq!(spend_txn.len(), 3);
5803         check_spends!(spend_txn[0], local_txn[0]);
5804         assert_eq!(spend_txn[1].input.len(), 1);
5805         check_spends!(spend_txn[1], htlc_timeout);
5806         assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5807         assert_eq!(spend_txn[2].input.len(), 2);
5808         check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5809         assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5810                 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5811 }
5812
5813 #[test]
5814 fn test_key_derivation_params() {
5815         // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5816         // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5817         // let us re-derive the channel key set to then derive a delayed_payment_key.
5818
5819         let chanmon_cfgs = create_chanmon_cfgs(3);
5820
5821         // We manually create the node configuration to backup the seed.
5822         let seed = [42; 32];
5823         let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5824         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);
5825         let network_graph = NetworkGraph::new(chanmon_cfgs[0].chain_source.genesis_hash, &chanmon_cfgs[0].logger);
5826         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, node_seed: seed, features: channelmanager::provided_init_features() };
5827         let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5828         node_cfgs.remove(0);
5829         node_cfgs.insert(0, node);
5830
5831         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5832         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5833
5834         // Create some initial channels
5835         // Create a dummy channel to advance index by one and thus test re-derivation correctness
5836         // for node 0
5837         let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5838         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5839         assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5840
5841         // Ensure all nodes are at the same height
5842         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5843         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5844         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5845         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5846
5847         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5848         let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5849         let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5850         assert_eq!(local_txn_1[0].input.len(), 1);
5851         check_spends!(local_txn_1[0], chan_1.3);
5852
5853         // We check funding pubkey are unique
5854         let (from_0_funding_key_0, from_0_funding_key_1) = (PublicKey::from_slice(&local_txn_0[0].input[0].witness.to_vec()[3][2..35]), PublicKey::from_slice(&local_txn_0[0].input[0].witness.to_vec()[3][36..69]));
5855         let (from_1_funding_key_0, from_1_funding_key_1) = (PublicKey::from_slice(&local_txn_1[0].input[0].witness.to_vec()[3][2..35]), PublicKey::from_slice(&local_txn_1[0].input[0].witness.to_vec()[3][36..69]));
5856         if from_0_funding_key_0 == from_1_funding_key_0
5857             || from_0_funding_key_0 == from_1_funding_key_1
5858             || from_0_funding_key_1 == from_1_funding_key_0
5859             || from_0_funding_key_1 == from_1_funding_key_1 {
5860                 panic!("Funding pubkeys aren't unique");
5861         }
5862
5863         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5864         mine_transaction(&nodes[0], &local_txn_1[0]);
5865         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5866         check_closed_broadcast!(nodes[0], true);
5867         check_added_monitors!(nodes[0], 1);
5868         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5869
5870         let htlc_timeout = {
5871                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5872                 assert_eq!(node_txn[1].input.len(), 1);
5873                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5874                 check_spends!(node_txn[1], local_txn_1[0]);
5875                 node_txn[1].clone()
5876         };
5877
5878         mine_transaction(&nodes[0], &htlc_timeout);
5879         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5880         expect_payment_failed!(nodes[0], our_payment_hash, false);
5881
5882         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5883         let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5884         let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5885         assert_eq!(spend_txn.len(), 3);
5886         check_spends!(spend_txn[0], local_txn_1[0]);
5887         assert_eq!(spend_txn[1].input.len(), 1);
5888         check_spends!(spend_txn[1], htlc_timeout);
5889         assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5890         assert_eq!(spend_txn[2].input.len(), 2);
5891         check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5892         assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5893                 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5894 }
5895
5896 #[test]
5897 fn test_static_output_closing_tx() {
5898         let chanmon_cfgs = create_chanmon_cfgs(2);
5899         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5900         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5901         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5902
5903         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5904
5905         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5906         let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5907
5908         mine_transaction(&nodes[0], &closing_tx);
5909         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5910         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5911
5912         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5913         assert_eq!(spend_txn.len(), 1);
5914         check_spends!(spend_txn[0], closing_tx);
5915
5916         mine_transaction(&nodes[1], &closing_tx);
5917         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5918         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5919
5920         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5921         assert_eq!(spend_txn.len(), 1);
5922         check_spends!(spend_txn[0], closing_tx);
5923 }
5924
5925 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5926         let chanmon_cfgs = create_chanmon_cfgs(2);
5927         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5928         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5929         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5930         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5931
5932         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3_000_000 });
5933
5934         // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5935         // present in B's local commitment transaction, but none of A's commitment transactions.
5936         nodes[1].node.claim_funds(payment_preimage);
5937         check_added_monitors!(nodes[1], 1);
5938         expect_payment_claimed!(nodes[1], payment_hash, if use_dust { 50000 } else { 3_000_000 });
5939
5940         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5941         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5942         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
5943
5944         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5945         check_added_monitors!(nodes[0], 1);
5946         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5947         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5948         check_added_monitors!(nodes[1], 1);
5949
5950         let starting_block = nodes[1].best_block_info();
5951         let mut block = Block {
5952                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
5953                 txdata: vec![],
5954         };
5955         for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5956                 connect_block(&nodes[1], &block);
5957                 block.header.prev_blockhash = block.block_hash();
5958         }
5959         test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5960         check_closed_broadcast!(nodes[1], true);
5961         check_added_monitors!(nodes[1], 1);
5962         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5963 }
5964
5965 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5966         let chanmon_cfgs = create_chanmon_cfgs(2);
5967         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5968         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5969         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5970         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5971
5972         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5973         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
5974         check_added_monitors!(nodes[0], 1);
5975
5976         let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5977
5978         // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5979         // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5980         // to "time out" the HTLC.
5981
5982         let starting_block = nodes[1].best_block_info();
5983         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
5984
5985         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5986                 connect_block(&nodes[0], &Block { header, txdata: Vec::new()});
5987                 header.prev_blockhash = header.block_hash();
5988         }
5989         test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5990         check_closed_broadcast!(nodes[0], true);
5991         check_added_monitors!(nodes[0], 1);
5992         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5993 }
5994
5995 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5996         let chanmon_cfgs = create_chanmon_cfgs(3);
5997         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5998         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5999         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6000         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6001
6002         // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
6003         // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
6004         // Also optionally test that we *don't* fail the channel in case the commitment transaction was
6005         // actually revoked.
6006         let htlc_value = if use_dust { 50000 } else { 3000000 };
6007         let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
6008         nodes[1].node.fail_htlc_backwards(&our_payment_hash);
6009         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
6010         check_added_monitors!(nodes[1], 1);
6011
6012         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6013         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
6014         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
6015         check_added_monitors!(nodes[0], 1);
6016         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6017         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
6018         check_added_monitors!(nodes[1], 1);
6019         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
6020         check_added_monitors!(nodes[1], 1);
6021         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
6022
6023         if check_revoke_no_close {
6024                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
6025                 check_added_monitors!(nodes[0], 1);
6026         }
6027
6028         let starting_block = nodes[1].best_block_info();
6029         let mut block = Block {
6030                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
6031                 txdata: vec![],
6032         };
6033         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
6034                 connect_block(&nodes[0], &block);
6035                 block.header.prev_blockhash = block.block_hash();
6036         }
6037         if !check_revoke_no_close {
6038                 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
6039                 check_closed_broadcast!(nodes[0], true);
6040                 check_added_monitors!(nodes[0], 1);
6041                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6042         } else {
6043                 let events = nodes[0].node.get_and_clear_pending_events();
6044                 assert_eq!(events.len(), 2);
6045                 if let Event::PaymentPathFailed { ref payment_hash, .. } = events[0] {
6046                         assert_eq!(*payment_hash, our_payment_hash);
6047                 } else { panic!("Unexpected event"); }
6048                 if let Event::PaymentFailed { ref payment_hash, .. } = events[1] {
6049                         assert_eq!(*payment_hash, our_payment_hash);
6050                 } else { panic!("Unexpected event"); }
6051         }
6052 }
6053
6054 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
6055 // There are only a few cases to test here:
6056 //  * its not really normative behavior, but we test that below-dust HTLCs "included" in
6057 //    broadcastable commitment transactions result in channel closure,
6058 //  * its included in an unrevoked-but-previous remote commitment transaction,
6059 //  * its included in the latest remote or local commitment transactions.
6060 // We test each of the three possible commitment transactions individually and use both dust and
6061 // non-dust HTLCs.
6062 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
6063 // assume they are handled the same across all six cases, as both outbound and inbound failures are
6064 // tested for at least one of the cases in other tests.
6065 #[test]
6066 fn htlc_claim_single_commitment_only_a() {
6067         do_htlc_claim_local_commitment_only(true);
6068         do_htlc_claim_local_commitment_only(false);
6069
6070         do_htlc_claim_current_remote_commitment_only(true);
6071         do_htlc_claim_current_remote_commitment_only(false);
6072 }
6073
6074 #[test]
6075 fn htlc_claim_single_commitment_only_b() {
6076         do_htlc_claim_previous_remote_commitment_only(true, false);
6077         do_htlc_claim_previous_remote_commitment_only(false, false);
6078         do_htlc_claim_previous_remote_commitment_only(true, true);
6079         do_htlc_claim_previous_remote_commitment_only(false, true);
6080 }
6081
6082 #[test]
6083 #[should_panic]
6084 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
6085         let chanmon_cfgs = create_chanmon_cfgs(2);
6086         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6087         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6088         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6089         // Force duplicate randomness for every get-random call
6090         for node in nodes.iter() {
6091                 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
6092         }
6093
6094         // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
6095         let channel_value_satoshis=10000;
6096         let push_msat=10001;
6097         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
6098         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6099         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &node0_to_1_send_open_channel);
6100         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
6101
6102         // Create a second channel with the same random values. This used to panic due to a colliding
6103         // channel_id, but now panics due to a colliding outbound SCID alias.
6104         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6105 }
6106
6107 #[test]
6108 fn bolt2_open_channel_sending_node_checks_part2() {
6109         let chanmon_cfgs = create_chanmon_cfgs(2);
6110         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6111         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6112         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6113
6114         // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
6115         let channel_value_satoshis=2^24;
6116         let push_msat=10001;
6117         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6118
6119         // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
6120         let channel_value_satoshis=10000;
6121         // Test when push_msat is equal to 1000 * funding_satoshis.
6122         let push_msat=1000*channel_value_satoshis+1;
6123         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6124
6125         // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
6126         let channel_value_satoshis=10000;
6127         let push_msat=10001;
6128         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
6129         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6130         assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
6131
6132         // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
6133         // 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
6134         assert!(node0_to_1_send_open_channel.channel_flags<=1);
6135
6136         // 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.
6137         assert!(BREAKDOWN_TIMEOUT>0);
6138         assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
6139
6140         // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
6141         let chain_hash=genesis_block(Network::Testnet).header.block_hash();
6142         assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
6143
6144         // 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.
6145         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
6146         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
6147         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
6148         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
6149         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
6150 }
6151
6152 #[test]
6153 fn bolt2_open_channel_sane_dust_limit() {
6154         let chanmon_cfgs = create_chanmon_cfgs(2);
6155         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6156         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6157         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6158
6159         let channel_value_satoshis=1000000;
6160         let push_msat=10001;
6161         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
6162         let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6163         node0_to_1_send_open_channel.dust_limit_satoshis = 547;
6164         node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
6165
6166         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &node0_to_1_send_open_channel);
6167         let events = nodes[1].node.get_and_clear_pending_msg_events();
6168         let err_msg = match events[0] {
6169                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
6170                         msg.clone()
6171                 },
6172                 _ => panic!("Unexpected event"),
6173         };
6174         assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
6175 }
6176
6177 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
6178 // originated from our node, its failure is surfaced to the user. We trigger this failure to
6179 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
6180 // is no longer affordable once it's freed.
6181 #[test]
6182 fn test_fail_holding_cell_htlc_upon_free() {
6183         let chanmon_cfgs = create_chanmon_cfgs(2);
6184         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6185         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6186         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6187         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6188
6189         // First nodes[0] generates an update_fee, setting the channel's
6190         // pending_update_fee.
6191         {
6192                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6193                 *feerate_lock += 20;
6194         }
6195         nodes[0].node.timer_tick_occurred();
6196         check_added_monitors!(nodes[0], 1);
6197
6198         let events = nodes[0].node.get_and_clear_pending_msg_events();
6199         assert_eq!(events.len(), 1);
6200         let (update_msg, commitment_signed) = match events[0] {
6201                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6202                         (update_fee.as_ref(), commitment_signed)
6203                 },
6204                 _ => panic!("Unexpected event"),
6205         };
6206
6207         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6208
6209         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6210         let channel_reserve = chan_stat.channel_reserve_msat;
6211         let feerate = get_feerate!(nodes[0], chan.2);
6212         let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6213
6214         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6215         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6216         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6217
6218         // Send a payment which passes reserve checks but gets stuck in the holding cell.
6219         let our_payment_id = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6220         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6221         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6222
6223         // Flush the pending fee update.
6224         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6225         let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6226         check_added_monitors!(nodes[1], 1);
6227         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
6228         check_added_monitors!(nodes[0], 1);
6229
6230         // Upon receipt of the RAA, there will be an attempt to resend the holding cell
6231         // HTLC, but now that the fee has been raised the payment will now fail, causing
6232         // us to surface its failure to the user.
6233         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6234         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6235         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);
6236         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 {}",
6237                 hex::encode(our_payment_hash.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6238         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6239
6240         // Check that the payment failed to be sent out.
6241         let events = nodes[0].node.get_and_clear_pending_events();
6242         assert_eq!(events.len(), 1);
6243         match &events[0] {
6244                 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, ref network_update, ref all_paths_failed, ref short_channel_id, .. } => {
6245                         assert_eq!(our_payment_id, *payment_id.as_ref().unwrap());
6246                         assert_eq!(our_payment_hash.clone(), *payment_hash);
6247                         assert_eq!(*payment_failed_permanently, false);
6248                         assert_eq!(*all_paths_failed, true);
6249                         assert_eq!(*network_update, None);
6250                         assert_eq!(*short_channel_id, Some(route.paths[0][0].short_channel_id));
6251                 },
6252                 _ => panic!("Unexpected event"),
6253         }
6254 }
6255
6256 // Test that if multiple HTLCs are released from the holding cell and one is
6257 // valid but the other is no longer valid upon release, the valid HTLC can be
6258 // successfully completed while the other one fails as expected.
6259 #[test]
6260 fn test_free_and_fail_holding_cell_htlcs() {
6261         let chanmon_cfgs = create_chanmon_cfgs(2);
6262         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6263         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6264         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6265         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6266
6267         // First nodes[0] generates an update_fee, setting the channel's
6268         // pending_update_fee.
6269         {
6270                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6271                 *feerate_lock += 200;
6272         }
6273         nodes[0].node.timer_tick_occurred();
6274         check_added_monitors!(nodes[0], 1);
6275
6276         let events = nodes[0].node.get_and_clear_pending_msg_events();
6277         assert_eq!(events.len(), 1);
6278         let (update_msg, commitment_signed) = match events[0] {
6279                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6280                         (update_fee.as_ref(), commitment_signed)
6281                 },
6282                 _ => panic!("Unexpected event"),
6283         };
6284
6285         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6286
6287         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6288         let channel_reserve = chan_stat.channel_reserve_msat;
6289         let feerate = get_feerate!(nodes[0], chan.2);
6290         let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6291
6292         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6293         let amt_1 = 20000;
6294         let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors) - amt_1;
6295         let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
6296         let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
6297
6298         // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6299         nodes[0].node.send_payment(&route_1, payment_hash_1, &Some(payment_secret_1)).unwrap();
6300         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6301         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6302         let payment_id_2 = nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
6303         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6304         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6305
6306         // Flush the pending fee update.
6307         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6308         let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6309         check_added_monitors!(nodes[1], 1);
6310         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6311         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6312         check_added_monitors!(nodes[0], 2);
6313
6314         // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6315         // but now that the fee has been raised the second payment will now fail, causing us
6316         // to surface its failure to the user. The first payment should succeed.
6317         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6318         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6319         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);
6320         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 {}",
6321                 hex::encode(payment_hash_2.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6322         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6323
6324         // Check that the second payment failed to be sent out.
6325         let events = nodes[0].node.get_and_clear_pending_events();
6326         assert_eq!(events.len(), 1);
6327         match &events[0] {
6328                 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, ref network_update, ref all_paths_failed, ref short_channel_id, .. } => {
6329                         assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
6330                         assert_eq!(payment_hash_2.clone(), *payment_hash);
6331                         assert_eq!(*payment_failed_permanently, false);
6332                         assert_eq!(*all_paths_failed, true);
6333                         assert_eq!(*network_update, None);
6334                         assert_eq!(*short_channel_id, Some(route_2.paths[0][0].short_channel_id));
6335                 },
6336                 _ => panic!("Unexpected event"),
6337         }
6338
6339         // Complete the first payment and the RAA from the fee update.
6340         let (payment_event, send_raa_event) = {
6341                 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6342                 assert_eq!(msgs.len(), 2);
6343                 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6344         };
6345         let raa = match send_raa_event {
6346                 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6347                 _ => panic!("Unexpected event"),
6348         };
6349         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6350         check_added_monitors!(nodes[1], 1);
6351         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6352         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6353         let events = nodes[1].node.get_and_clear_pending_events();
6354         assert_eq!(events.len(), 1);
6355         match events[0] {
6356                 Event::PendingHTLCsForwardable { .. } => {},
6357                 _ => panic!("Unexpected event"),
6358         }
6359         nodes[1].node.process_pending_htlc_forwards();
6360         let events = nodes[1].node.get_and_clear_pending_events();
6361         assert_eq!(events.len(), 1);
6362         match events[0] {
6363                 Event::PaymentReceived { .. } => {},
6364                 _ => panic!("Unexpected event"),
6365         }
6366         nodes[1].node.claim_funds(payment_preimage_1);
6367         check_added_monitors!(nodes[1], 1);
6368         expect_payment_claimed!(nodes[1], payment_hash_1, amt_1);
6369
6370         let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6371         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6372         commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6373         expect_payment_sent!(nodes[0], payment_preimage_1);
6374 }
6375
6376 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6377 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6378 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6379 // once it's freed.
6380 #[test]
6381 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6382         let chanmon_cfgs = create_chanmon_cfgs(3);
6383         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6384         // When this test was written, the default base fee floated based on the HTLC count.
6385         // It is now fixed, so we simply set the fee to the expected value here.
6386         let mut config = test_default_channel_config();
6387         config.channel_config.forwarding_fee_base_msat = 196;
6388         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
6389         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6390         let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6391         let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6392
6393         // First nodes[1] generates an update_fee, setting the channel's
6394         // pending_update_fee.
6395         {
6396                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
6397                 *feerate_lock += 20;
6398         }
6399         nodes[1].node.timer_tick_occurred();
6400         check_added_monitors!(nodes[1], 1);
6401
6402         let events = nodes[1].node.get_and_clear_pending_msg_events();
6403         assert_eq!(events.len(), 1);
6404         let (update_msg, commitment_signed) = match events[0] {
6405                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6406                         (update_fee.as_ref(), commitment_signed)
6407                 },
6408                 _ => panic!("Unexpected event"),
6409         };
6410
6411         nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6412
6413         let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
6414         let channel_reserve = chan_stat.channel_reserve_msat;
6415         let feerate = get_feerate!(nodes[0], chan_0_1.2);
6416         let opt_anchors = get_opt_anchors!(nodes[0], chan_0_1.2);
6417
6418         // Send a payment which passes reserve checks but gets stuck in the holding cell.
6419         let feemsat = 239;
6420         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
6421         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors) - total_routing_fee_msat;
6422         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
6423         let payment_event = {
6424                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6425                 check_added_monitors!(nodes[0], 1);
6426
6427                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6428                 assert_eq!(events.len(), 1);
6429
6430                 SendEvent::from_event(events.remove(0))
6431         };
6432         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6433         check_added_monitors!(nodes[1], 0);
6434         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6435         expect_pending_htlcs_forwardable!(nodes[1]);
6436
6437         chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
6438         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6439
6440         // Flush the pending fee update.
6441         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6442         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6443         check_added_monitors!(nodes[2], 1);
6444         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6445         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6446         check_added_monitors!(nodes[1], 2);
6447
6448         // A final RAA message is generated to finalize the fee update.
6449         let events = nodes[1].node.get_and_clear_pending_msg_events();
6450         assert_eq!(events.len(), 1);
6451
6452         let raa_msg = match &events[0] {
6453                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6454                         msg.clone()
6455                 },
6456                 _ => panic!("Unexpected event"),
6457         };
6458
6459         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6460         check_added_monitors!(nodes[2], 1);
6461         assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6462
6463         // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6464         let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6465         assert_eq!(process_htlc_forwards_event.len(), 2);
6466         match &process_htlc_forwards_event[0] {
6467                 &Event::PendingHTLCsForwardable { .. } => {},
6468                 _ => panic!("Unexpected event"),
6469         }
6470
6471         // In response, we call ChannelManager's process_pending_htlc_forwards
6472         nodes[1].node.process_pending_htlc_forwards();
6473         check_added_monitors!(nodes[1], 1);
6474
6475         // This causes the HTLC to be failed backwards.
6476         let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6477         assert_eq!(fail_event.len(), 1);
6478         let (fail_msg, commitment_signed) = match &fail_event[0] {
6479                 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6480                         assert_eq!(updates.update_add_htlcs.len(), 0);
6481                         assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6482                         assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6483                         assert_eq!(updates.update_fail_htlcs.len(), 1);
6484                         (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6485                 },
6486                 _ => panic!("Unexpected event"),
6487         };
6488
6489         // Pass the failure messages back to nodes[0].
6490         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6491         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6492
6493         // Complete the HTLC failure+removal process.
6494         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6495         check_added_monitors!(nodes[0], 1);
6496         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6497         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6498         check_added_monitors!(nodes[1], 2);
6499         let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6500         assert_eq!(final_raa_event.len(), 1);
6501         let raa = match &final_raa_event[0] {
6502                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6503                 _ => panic!("Unexpected event"),
6504         };
6505         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6506         expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6507         check_added_monitors!(nodes[0], 1);
6508 }
6509
6510 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6511 // 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.
6512 //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.
6513
6514 #[test]
6515 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6516         //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6517         let chanmon_cfgs = create_chanmon_cfgs(2);
6518         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6519         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6520         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6521         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6522
6523         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6524         route.paths[0][0].fee_msat = 100;
6525
6526         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6527                 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6528         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6529         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6530 }
6531
6532 #[test]
6533 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6534         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6535         let chanmon_cfgs = create_chanmon_cfgs(2);
6536         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6537         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6538         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6539         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6540
6541         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6542         route.paths[0][0].fee_msat = 0;
6543         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6544                 assert_eq!(err, "Cannot send 0-msat HTLC"));
6545
6546         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6547         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6548 }
6549
6550 #[test]
6551 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6552         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6553         let chanmon_cfgs = create_chanmon_cfgs(2);
6554         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6555         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6556         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6557         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6558
6559         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6560         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6561         check_added_monitors!(nodes[0], 1);
6562         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6563         updates.update_add_htlcs[0].amount_msat = 0;
6564
6565         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6566         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6567         check_closed_broadcast!(nodes[1], true).unwrap();
6568         check_added_monitors!(nodes[1], 1);
6569         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
6570 }
6571
6572 #[test]
6573 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6574         //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6575         //It is enforced when constructing a route.
6576         let chanmon_cfgs = create_chanmon_cfgs(2);
6577         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6578         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6579         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6580         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6581
6582         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
6583                 .with_features(channelmanager::provided_invoice_features());
6584         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000, 0);
6585         route.paths[0].last_mut().unwrap().cltv_expiry_delta = 500000001;
6586         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::RouteError { ref err },
6587                 assert_eq!(err, &"Channel CLTV overflowed?"));
6588 }
6589
6590 #[test]
6591 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6592         //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.
6593         //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6594         //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6595         let chanmon_cfgs = create_chanmon_cfgs(2);
6596         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6597         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6598         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6599         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6600         let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6601
6602         for i in 0..max_accepted_htlcs {
6603                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6604                 let payment_event = {
6605                         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6606                         check_added_monitors!(nodes[0], 1);
6607
6608                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6609                         assert_eq!(events.len(), 1);
6610                         if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6611                                 assert_eq!(htlcs[0].htlc_id, i);
6612                         } else {
6613                                 assert!(false);
6614                         }
6615                         SendEvent::from_event(events.remove(0))
6616                 };
6617                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6618                 check_added_monitors!(nodes[1], 0);
6619                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6620
6621                 expect_pending_htlcs_forwardable!(nodes[1]);
6622                 expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6623         }
6624         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6625         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6626                 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6627
6628         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6629         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6630 }
6631
6632 #[test]
6633 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6634         //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.
6635         let chanmon_cfgs = create_chanmon_cfgs(2);
6636         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6637         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6638         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6639         let channel_value = 100000;
6640         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6641         let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6642
6643         send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6644
6645         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6646         // Manually create a route over our max in flight (which our router normally automatically
6647         // limits us to.
6648         route.paths[0][0].fee_msat =  max_in_flight + 1;
6649         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6650                 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)));
6651
6652         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6653         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);
6654
6655         send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6656 }
6657
6658 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6659 #[test]
6660 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6661         //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6662         let chanmon_cfgs = create_chanmon_cfgs(2);
6663         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6664         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6665         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6666         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6667         let htlc_minimum_msat: u64;
6668         {
6669                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6670                 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6671                 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6672         }
6673
6674         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6675         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6676         check_added_monitors!(nodes[0], 1);
6677         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6678         updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6679         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6680         assert!(nodes[1].node.list_channels().is_empty());
6681         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6682         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()));
6683         check_added_monitors!(nodes[1], 1);
6684         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6685 }
6686
6687 #[test]
6688 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6689         //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
6690         let chanmon_cfgs = create_chanmon_cfgs(2);
6691         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6692         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6693         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6694         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6695
6696         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6697         let channel_reserve = chan_stat.channel_reserve_msat;
6698         let feerate = get_feerate!(nodes[0], chan.2);
6699         let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6700         // The 2* and +1 are for the fee spike reserve.
6701         let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6702
6703         let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6704         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6705         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6706         check_added_monitors!(nodes[0], 1);
6707         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6708
6709         // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6710         // at this time channel-initiatee receivers are not required to enforce that senders
6711         // respect the fee_spike_reserve.
6712         updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6713         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6714
6715         assert!(nodes[1].node.list_channels().is_empty());
6716         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6717         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6718         check_added_monitors!(nodes[1], 1);
6719         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6720 }
6721
6722 #[test]
6723 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6724         //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6725         //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6726         let chanmon_cfgs = create_chanmon_cfgs(2);
6727         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6728         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6729         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6730         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6731
6732         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3999999);
6733         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6734         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6735         let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6736         let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &Some(our_payment_secret), cur_height, &None).unwrap();
6737         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6738
6739         let mut msg = msgs::UpdateAddHTLC {
6740                 channel_id: chan.2,
6741                 htlc_id: 0,
6742                 amount_msat: 1000,
6743                 payment_hash: our_payment_hash,
6744                 cltv_expiry: htlc_cltv,
6745                 onion_routing_packet: onion_packet.clone(),
6746         };
6747
6748         for i in 0..super::channel::OUR_MAX_HTLCS {
6749                 msg.htlc_id = i as u64;
6750                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6751         }
6752         msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6753         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6754
6755         assert!(nodes[1].node.list_channels().is_empty());
6756         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6757         assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6758         check_added_monitors!(nodes[1], 1);
6759         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6760 }
6761
6762 #[test]
6763 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6764         //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6765         let chanmon_cfgs = create_chanmon_cfgs(2);
6766         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6767         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6768         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6769         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6770
6771         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6772         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6773         check_added_monitors!(nodes[0], 1);
6774         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6775         updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6776         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6777
6778         assert!(nodes[1].node.list_channels().is_empty());
6779         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6780         assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6781         check_added_monitors!(nodes[1], 1);
6782         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6783 }
6784
6785 #[test]
6786 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6787         //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6788         let chanmon_cfgs = create_chanmon_cfgs(2);
6789         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6790         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6791         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6792
6793         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6794         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6795         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6796         check_added_monitors!(nodes[0], 1);
6797         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6798         updates.update_add_htlcs[0].cltv_expiry = 500000000;
6799         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6800
6801         assert!(nodes[1].node.list_channels().is_empty());
6802         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6803         assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6804         check_added_monitors!(nodes[1], 1);
6805         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6806 }
6807
6808 #[test]
6809 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6810         //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6811         // We test this by first testing that that repeated HTLCs pass commitment signature checks
6812         // after disconnect and that non-sequential htlc_ids result in a channel failure.
6813         let chanmon_cfgs = create_chanmon_cfgs(2);
6814         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6815         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6816         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6817
6818         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6819         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6820         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6821         check_added_monitors!(nodes[0], 1);
6822         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6823         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6824
6825         //Disconnect and Reconnect
6826         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6827         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6828         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
6829         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6830         assert_eq!(reestablish_1.len(), 1);
6831         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
6832         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6833         assert_eq!(reestablish_2.len(), 1);
6834         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6835         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6836         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6837         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6838
6839         //Resend HTLC
6840         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6841         assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6842         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6843         check_added_monitors!(nodes[1], 1);
6844         let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6845
6846         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6847
6848         assert!(nodes[1].node.list_channels().is_empty());
6849         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6850         assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6851         check_added_monitors!(nodes[1], 1);
6852         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6853 }
6854
6855 #[test]
6856 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6857         //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.
6858
6859         let chanmon_cfgs = create_chanmon_cfgs(2);
6860         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6861         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6862         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6863         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6864         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6865         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6866
6867         check_added_monitors!(nodes[0], 1);
6868         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6869         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6870
6871         let update_msg = msgs::UpdateFulfillHTLC{
6872                 channel_id: chan.2,
6873                 htlc_id: 0,
6874                 payment_preimage: our_payment_preimage,
6875         };
6876
6877         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6878
6879         assert!(nodes[0].node.list_channels().is_empty());
6880         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6881         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()));
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_update_fail_htlc_before_commitment() {
6888         //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.
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 mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6894         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6895
6896         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6897         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6898         check_added_monitors!(nodes[0], 1);
6899         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6900         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6901
6902         let update_msg = msgs::UpdateFailHTLC{
6903                 channel_id: chan.2,
6904                 htlc_id: 0,
6905                 reason: msgs::OnionErrorPacket { data: Vec::new()},
6906         };
6907
6908         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6909
6910         assert!(nodes[0].node.list_channels().is_empty());
6911         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6912         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()));
6913         check_added_monitors!(nodes[0], 1);
6914         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6915 }
6916
6917 #[test]
6918 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6919         //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.
6920
6921         let chanmon_cfgs = create_chanmon_cfgs(2);
6922         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6923         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6924         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6925         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6926
6927         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6928         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6929         check_added_monitors!(nodes[0], 1);
6930         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6931         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6932         let update_msg = msgs::UpdateFailMalformedHTLC{
6933                 channel_id: chan.2,
6934                 htlc_id: 0,
6935                 sha256_of_onion: [1; 32],
6936                 failure_code: 0x8000,
6937         };
6938
6939         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6940
6941         assert!(nodes[0].node.list_channels().is_empty());
6942         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6943         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()));
6944         check_added_monitors!(nodes[0], 1);
6945         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6946 }
6947
6948 #[test]
6949 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6950         //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6951
6952         let chanmon_cfgs = create_chanmon_cfgs(2);
6953         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6954         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6955         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6956         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6957
6958         let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6959
6960         nodes[1].node.claim_funds(our_payment_preimage);
6961         check_added_monitors!(nodes[1], 1);
6962         expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6963
6964         let events = nodes[1].node.get_and_clear_pending_msg_events();
6965         assert_eq!(events.len(), 1);
6966         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6967                 match events[0] {
6968                         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, .. } } => {
6969                                 assert!(update_add_htlcs.is_empty());
6970                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6971                                 assert!(update_fail_htlcs.is_empty());
6972                                 assert!(update_fail_malformed_htlcs.is_empty());
6973                                 assert!(update_fee.is_none());
6974                                 update_fulfill_htlcs[0].clone()
6975                         },
6976                         _ => panic!("Unexpected event"),
6977                 }
6978         };
6979
6980         update_fulfill_msg.htlc_id = 1;
6981
6982         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6983
6984         assert!(nodes[0].node.list_channels().is_empty());
6985         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6986         assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6987         check_added_monitors!(nodes[0], 1);
6988         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6989 }
6990
6991 #[test]
6992 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6993         //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.
6994
6995         let chanmon_cfgs = create_chanmon_cfgs(2);
6996         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6997         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6998         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6999         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7000
7001         let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
7002
7003         nodes[1].node.claim_funds(our_payment_preimage);
7004         check_added_monitors!(nodes[1], 1);
7005         expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
7006
7007         let events = nodes[1].node.get_and_clear_pending_msg_events();
7008         assert_eq!(events.len(), 1);
7009         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
7010                 match events[0] {
7011                         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, .. } } => {
7012                                 assert!(update_add_htlcs.is_empty());
7013                                 assert_eq!(update_fulfill_htlcs.len(), 1);
7014                                 assert!(update_fail_htlcs.is_empty());
7015                                 assert!(update_fail_malformed_htlcs.is_empty());
7016                                 assert!(update_fee.is_none());
7017                                 update_fulfill_htlcs[0].clone()
7018                         },
7019                         _ => panic!("Unexpected event"),
7020                 }
7021         };
7022
7023         update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
7024
7025         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
7026
7027         assert!(nodes[0].node.list_channels().is_empty());
7028         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
7029         assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
7030         check_added_monitors!(nodes[0], 1);
7031         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
7032 }
7033
7034 #[test]
7035 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
7036         //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.
7037
7038         let chanmon_cfgs = create_chanmon_cfgs(2);
7039         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7040         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7041         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7042         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7043
7044         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
7045         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7046         check_added_monitors!(nodes[0], 1);
7047
7048         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7049         updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
7050
7051         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
7052         check_added_monitors!(nodes[1], 0);
7053         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
7054
7055         let events = nodes[1].node.get_and_clear_pending_msg_events();
7056
7057         let mut update_msg: msgs::UpdateFailMalformedHTLC = {
7058                 match events[0] {
7059                         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, .. } } => {
7060                                 assert!(update_add_htlcs.is_empty());
7061                                 assert!(update_fulfill_htlcs.is_empty());
7062                                 assert!(update_fail_htlcs.is_empty());
7063                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
7064                                 assert!(update_fee.is_none());
7065                                 update_fail_malformed_htlcs[0].clone()
7066                         },
7067                         _ => panic!("Unexpected event"),
7068                 }
7069         };
7070         update_msg.failure_code &= !0x8000;
7071         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
7072
7073         assert!(nodes[0].node.list_channels().is_empty());
7074         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
7075         assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
7076         check_added_monitors!(nodes[0], 1);
7077         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
7078 }
7079
7080 #[test]
7081 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
7082         //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
7083         //    * 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.
7084
7085         let chanmon_cfgs = create_chanmon_cfgs(3);
7086         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7087         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7088         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7089         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7090         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7091
7092         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
7093
7094         //First hop
7095         let mut payment_event = {
7096                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7097                 check_added_monitors!(nodes[0], 1);
7098                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7099                 assert_eq!(events.len(), 1);
7100                 SendEvent::from_event(events.remove(0))
7101         };
7102         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7103         check_added_monitors!(nodes[1], 0);
7104         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7105         expect_pending_htlcs_forwardable!(nodes[1]);
7106         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7107         assert_eq!(events_2.len(), 1);
7108         check_added_monitors!(nodes[1], 1);
7109         payment_event = SendEvent::from_event(events_2.remove(0));
7110         assert_eq!(payment_event.msgs.len(), 1);
7111
7112         //Second Hop
7113         payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
7114         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
7115         check_added_monitors!(nodes[2], 0);
7116         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
7117
7118         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
7119         assert_eq!(events_3.len(), 1);
7120         let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
7121                 match events_3[0] {
7122                         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 } } => {
7123                                 assert!(update_add_htlcs.is_empty());
7124                                 assert!(update_fulfill_htlcs.is_empty());
7125                                 assert!(update_fail_htlcs.is_empty());
7126                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
7127                                 assert!(update_fee.is_none());
7128                                 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
7129                         },
7130                         _ => panic!("Unexpected event"),
7131                 }
7132         };
7133
7134         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
7135
7136         check_added_monitors!(nodes[1], 0);
7137         commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
7138         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
7139         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
7140         assert_eq!(events_4.len(), 1);
7141
7142         //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
7143         match events_4[0] {
7144                 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, .. } } => {
7145                         assert!(update_add_htlcs.is_empty());
7146                         assert!(update_fulfill_htlcs.is_empty());
7147                         assert_eq!(update_fail_htlcs.len(), 1);
7148                         assert!(update_fail_malformed_htlcs.is_empty());
7149                         assert!(update_fee.is_none());
7150                 },
7151                 _ => panic!("Unexpected event"),
7152         };
7153
7154         check_added_monitors!(nodes[1], 1);
7155 }
7156
7157 #[test]
7158 fn test_channel_failed_after_message_with_badonion_node_perm_bits_set() {
7159         let chanmon_cfgs = create_chanmon_cfgs(3);
7160         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7161         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7162         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7163         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7164         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7165
7166         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100_000);
7167
7168         // First hop
7169         let mut payment_event = {
7170                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7171                 check_added_monitors!(nodes[0], 1);
7172                 SendEvent::from_node(&nodes[0])
7173         };
7174
7175         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7176         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7177         expect_pending_htlcs_forwardable!(nodes[1]);
7178         check_added_monitors!(nodes[1], 1);
7179         payment_event = SendEvent::from_node(&nodes[1]);
7180         assert_eq!(payment_event.msgs.len(), 1);
7181
7182         // Second Hop
7183         payment_event.msgs[0].onion_routing_packet.version = 1; // Trigger an invalid_onion_version error
7184         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
7185         check_added_monitors!(nodes[2], 0);
7186         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
7187
7188         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
7189         assert_eq!(events_3.len(), 1);
7190         match events_3[0] {
7191                 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
7192                         let mut update_msg = updates.update_fail_malformed_htlcs[0].clone();
7193                         // Set the NODE bit (BADONION and PERM already set in invalid_onion_version error)
7194                         update_msg.failure_code |= 0x2000;
7195
7196                         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg);
7197                         commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true);
7198                 },
7199                 _ => panic!("Unexpected event"),
7200         }
7201
7202         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
7203                 vec![HTLCDestination::NextHopChannel {
7204                         node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
7205         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
7206         assert_eq!(events_4.len(), 1);
7207         check_added_monitors!(nodes[1], 1);
7208
7209         match events_4[0] {
7210                 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
7211                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
7212                         commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
7213                 },
7214                 _ => panic!("Unexpected event"),
7215         }
7216
7217         let events_5 = nodes[0].node.get_and_clear_pending_events();
7218         assert_eq!(events_5.len(), 1);
7219
7220         // Expect a PaymentPathFailed event with a ChannelFailure network update for the channel between
7221         // the node originating the error to its next hop.
7222         match events_5[0] {
7223                 Event::PaymentPathFailed { network_update:
7224                         Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent }), error_code, ..
7225                 } => {
7226                         assert_eq!(short_channel_id, chan_2.0.contents.short_channel_id);
7227                         assert!(is_permanent);
7228                         assert_eq!(error_code, Some(0x8000|0x4000|0x2000|4));
7229                 },
7230                 _ => panic!("Unexpected event"),
7231         }
7232
7233         // TODO: Test actual removal of channel from NetworkGraph when it's implemented.
7234 }
7235
7236 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
7237         // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
7238         // 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
7239         // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
7240
7241         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7242         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7243         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7244         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7245         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7246         let chan =create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7247
7248         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7249
7250         // We route 2 dust-HTLCs between A and B
7251         let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7252         let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7253         route_payment(&nodes[0], &[&nodes[1]], 1000000);
7254
7255         // Cache one local commitment tx as previous
7256         let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7257
7258         // Fail one HTLC to prune it in the will-be-latest-local commitment tx
7259         nodes[1].node.fail_htlc_backwards(&payment_hash_2);
7260         check_added_monitors!(nodes[1], 0);
7261         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
7262         check_added_monitors!(nodes[1], 1);
7263
7264         let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7265         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
7266         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
7267         check_added_monitors!(nodes[0], 1);
7268
7269         // Cache one local commitment tx as lastest
7270         let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7271
7272         let events = nodes[0].node.get_and_clear_pending_msg_events();
7273         match events[0] {
7274                 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
7275                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7276                 },
7277                 _ => panic!("Unexpected event"),
7278         }
7279         match events[1] {
7280                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
7281                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7282                 },
7283                 _ => panic!("Unexpected event"),
7284         }
7285
7286         assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
7287         // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7288         if announce_latest {
7289                 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
7290         } else {
7291                 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
7292         }
7293
7294         check_closed_broadcast!(nodes[0], true);
7295         check_added_monitors!(nodes[0], 1);
7296         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7297
7298         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7299         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7300         let events = nodes[0].node.get_and_clear_pending_events();
7301         // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
7302         assert_eq!(events.len(), 2);
7303         let mut first_failed = false;
7304         for event in events {
7305                 match event {
7306                         Event::PaymentPathFailed { payment_hash, .. } => {
7307                                 if payment_hash == payment_hash_1 {
7308                                         assert!(!first_failed);
7309                                         first_failed = true;
7310                                 } else {
7311                                         assert_eq!(payment_hash, payment_hash_2);
7312                                 }
7313                         }
7314                         _ => panic!("Unexpected event"),
7315                 }
7316         }
7317 }
7318
7319 #[test]
7320 fn test_failure_delay_dust_htlc_local_commitment() {
7321         do_test_failure_delay_dust_htlc_local_commitment(true);
7322         do_test_failure_delay_dust_htlc_local_commitment(false);
7323 }
7324
7325 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7326         // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7327         // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7328         // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7329         // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7330         // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7331         // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7332
7333         let chanmon_cfgs = create_chanmon_cfgs(3);
7334         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7335         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7336         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7337         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7338
7339         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7340
7341         let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7342         let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7343
7344         let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7345         let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7346
7347         // We revoked bs_commitment_tx
7348         if revoked {
7349                 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7350                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
7351         }
7352
7353         let mut timeout_tx = Vec::new();
7354         if local {
7355                 // We fail dust-HTLC 1 by broadcast of local commitment tx
7356                 mine_transaction(&nodes[0], &as_commitment_tx[0]);
7357                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7358                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7359                 expect_payment_failed!(nodes[0], dust_hash, false);
7360
7361                 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
7362                 check_closed_broadcast!(nodes[0], true);
7363                 check_added_monitors!(nodes[0], 1);
7364                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7365                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
7366                 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7367                 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7368                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7369                 mine_transaction(&nodes[0], &timeout_tx[0]);
7370                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7371                 expect_payment_failed!(nodes[0], non_dust_hash, false);
7372         } else {
7373                 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7374                 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
7375                 check_closed_broadcast!(nodes[0], true);
7376                 check_added_monitors!(nodes[0], 1);
7377                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7378                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7379
7380                 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7381                 timeout_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().drain(..)
7382                         .filter(|tx| tx.input[0].previous_output.txid == bs_commitment_tx[0].txid()).collect();
7383                 check_spends!(timeout_tx[0], bs_commitment_tx[0]);
7384                 // For both a revoked or non-revoked commitment transaction, after ANTI_REORG_DELAY the
7385                 // dust HTLC should have been failed.
7386                 expect_payment_failed!(nodes[0], dust_hash, false);
7387
7388                 if !revoked {
7389                         assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7390                 } else {
7391                         assert_eq!(timeout_tx[0].lock_time.0, 0);
7392                 }
7393                 // We fail non-dust-HTLC 2 by broadcast of local timeout/revocation-claim tx
7394                 mine_transaction(&nodes[0], &timeout_tx[0]);
7395                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7396                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7397                 expect_payment_failed!(nodes[0], non_dust_hash, false);
7398         }
7399 }
7400
7401 #[test]
7402 fn test_sweep_outbound_htlc_failure_update() {
7403         do_test_sweep_outbound_htlc_failure_update(false, true);
7404         do_test_sweep_outbound_htlc_failure_update(false, false);
7405         do_test_sweep_outbound_htlc_failure_update(true, false);
7406 }
7407
7408 #[test]
7409 fn test_user_configurable_csv_delay() {
7410         // We test our channel constructors yield errors when we pass them absurd csv delay
7411
7412         let mut low_our_to_self_config = UserConfig::default();
7413         low_our_to_self_config.channel_handshake_config.our_to_self_delay = 6;
7414         let mut high_their_to_self_config = UserConfig::default();
7415         high_their_to_self_config.channel_handshake_limits.their_to_self_delay = 100;
7416         let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7417         let chanmon_cfgs = create_chanmon_cfgs(2);
7418         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7419         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7420         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7421
7422         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7423         if let Err(error) = Channel::new_outbound(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7424                 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &channelmanager::provided_init_features(), 1000000, 1000000, 0,
7425                 &low_our_to_self_config, 0, 42)
7426         {
7427                 match error {
7428                         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())); },
7429                         _ => panic!("Unexpected event"),
7430                 }
7431         } else { assert!(false) }
7432
7433         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7434         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7435         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7436         open_channel.to_self_delay = 200;
7437         if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7438                 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &channelmanager::provided_init_features(), &open_channel, 0,
7439                 &low_our_to_self_config, 0, &nodes[0].logger, 42)
7440         {
7441                 match error {
7442                         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()));  },
7443                         _ => panic!("Unexpected event"),
7444                 }
7445         } else { assert!(false); }
7446
7447         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7448         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7449         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id()));
7450         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7451         accept_channel.to_self_delay = 200;
7452         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_channel);
7453         let reason_msg;
7454         if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7455                 match action {
7456                         &ErrorAction::SendErrorMessage { ref msg } => {
7457                                 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()));
7458                                 reason_msg = msg.data.clone();
7459                         },
7460                         _ => { panic!(); }
7461                 }
7462         } else { panic!(); }
7463         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg });
7464
7465         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7466         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7467         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7468         open_channel.to_self_delay = 200;
7469         if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7470                 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &channelmanager::provided_init_features(), &open_channel, 0,
7471                 &high_their_to_self_config, 0, &nodes[0].logger, 42)
7472         {
7473                 match error {
7474                         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())); },
7475                         _ => panic!("Unexpected event"),
7476                 }
7477         } else { assert!(false); }
7478 }
7479
7480 fn do_test_data_loss_protect(reconnect_panicing: bool) {
7481         // When we get a data_loss_protect proving we're behind, we immediately panic as the
7482         // chain::Watch API requirements have been violated (e.g. the user restored from a backup). The
7483         // panic message informs the user they should force-close without broadcasting, which is tested
7484         // if `reconnect_panicing` is not set.
7485         let persister;
7486         let logger;
7487         let fee_estimator;
7488         let tx_broadcaster;
7489         let chain_source;
7490         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7491         // We broadcast during Drop because chanmon is out of sync with chanmgr, which would cause a panic
7492         // during signing due to revoked tx
7493         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7494         let keys_manager = &chanmon_cfgs[0].keys_manager;
7495         let monitor;
7496         let node_state_0;
7497         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7498         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7499         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7500
7501         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7502
7503         // Cache node A state before any channel update
7504         let previous_node_state = nodes[0].node.encode();
7505         let mut previous_chain_monitor_state = test_utils::TestVecWriter(Vec::new());
7506         get_monitor!(nodes[0], chan.2).write(&mut previous_chain_monitor_state).unwrap();
7507
7508         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7509         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7510
7511         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7512         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7513
7514         // Restore node A from previous state
7515         logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7516         let mut chain_monitor = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut io::Cursor::new(previous_chain_monitor_state.0), keys_manager).unwrap().1;
7517         chain_source = test_utils::TestChainSource::new(Network::Testnet);
7518         tx_broadcaster = test_utils::TestBroadcaster { txn_broadcasted: Mutex::new(Vec::new()), blocks: Arc::new(Mutex::new(Vec::new())) };
7519         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
7520         persister = test_utils::TestPersister::new();
7521         monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &tx_broadcaster, &logger, &fee_estimator, &persister, keys_manager);
7522         node_state_0 = {
7523                 let mut channel_monitors = HashMap::new();
7524                 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chain_monitor);
7525                 <(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 {
7526                         keys_manager: keys_manager,
7527                         fee_estimator: &fee_estimator,
7528                         chain_monitor: &monitor,
7529                         logger: &logger,
7530                         tx_broadcaster: &tx_broadcaster,
7531                         default_config: UserConfig::default(),
7532                         channel_monitors,
7533                 }).unwrap().1
7534         };
7535         nodes[0].node = &node_state_0;
7536         assert!(monitor.watch_channel(OutPoint { txid: chan.3.txid(), index: 0 }, chain_monitor).is_ok());
7537         nodes[0].chain_monitor = &monitor;
7538         nodes[0].chain_source = &chain_source;
7539
7540         check_added_monitors!(nodes[0], 1);
7541
7542         if reconnect_panicing {
7543                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
7544                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
7545
7546                 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7547
7548                 // Check we close channel detecting A is fallen-behind
7549                 // Check that we sent the warning message when we detected that A has fallen behind,
7550                 // and give the possibility for A to recover from the warning.
7551                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7552                 let warn_msg = "Peer attempted to reestablish channel with a very old local commitment transaction".to_owned();
7553                 assert!(check_warn_msg!(nodes[1], nodes[0].node.get_our_node_id(), chan.2).contains(&warn_msg));
7554
7555                 {
7556                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7557                         // The node B should not broadcast the transaction to force close the channel!
7558                         assert!(node_txn.is_empty());
7559                 }
7560
7561                 let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7562                 // Check A panics upon seeing proof it has fallen behind.
7563                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7564                 return; // By this point we should have panic'ed!
7565         }
7566
7567         nodes[0].node.force_close_without_broadcasting_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
7568         check_added_monitors!(nodes[0], 1);
7569         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
7570         {
7571                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7572                 assert_eq!(node_txn.len(), 0);
7573         }
7574
7575         for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7576                 if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7577                 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7578                         match action {
7579                                 &ErrorAction::SendErrorMessage { ref msg } => {
7580                                         assert_eq!(msg.data, "Channel force-closed");
7581                                 },
7582                                 _ => panic!("Unexpected event!"),
7583                         }
7584                 } else {
7585                         panic!("Unexpected event {:?}", msg)
7586                 }
7587         }
7588
7589         // after the warning message sent by B, we should not able to
7590         // use the channel, or reconnect with success to the channel.
7591         assert!(nodes[0].node.list_usable_channels().is_empty());
7592         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
7593         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
7594         let retry_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7595
7596         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &retry_reestablish[0]);
7597         let mut err_msgs_0 = Vec::with_capacity(1);
7598         for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7599                 if let MessageSendEvent::HandleError { ref action, .. } = msg {
7600                         match action {
7601                                 &ErrorAction::SendErrorMessage { ref msg } => {
7602                                         assert_eq!(msg.data, "Failed to find corresponding channel");
7603                                         err_msgs_0.push(msg.clone());
7604                                 },
7605                                 _ => panic!("Unexpected event!"),
7606                         }
7607                 } else {
7608                         panic!("Unexpected event!");
7609                 }
7610         }
7611         assert_eq!(err_msgs_0.len(), 1);
7612         nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), &err_msgs_0[0]);
7613         assert!(nodes[1].node.list_usable_channels().is_empty());
7614         check_added_monitors!(nodes[1], 1);
7615         check_closed_event!(nodes[1], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "Failed to find corresponding channel".to_owned() });
7616         check_closed_broadcast!(nodes[1], false);
7617 }
7618
7619 #[test]
7620 #[should_panic]
7621 fn test_data_loss_protect_showing_stale_state_panics() {
7622         do_test_data_loss_protect(true);
7623 }
7624
7625 #[test]
7626 fn test_force_close_without_broadcast() {
7627         do_test_data_loss_protect(false);
7628 }
7629
7630 #[test]
7631 fn test_check_htlc_underpaying() {
7632         // Send payment through A -> B but A is maliciously
7633         // sending a probe payment (i.e less than expected value0
7634         // to B, B should refuse payment.
7635
7636         let chanmon_cfgs = create_chanmon_cfgs(2);
7637         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7638         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7639         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7640
7641         // Create some initial channels
7642         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7643
7644         let scorer = test_utils::TestScorer::with_penalty(0);
7645         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7646         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id()).with_features(channelmanager::provided_invoice_features());
7647         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();
7648         let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7649         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200).unwrap();
7650         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7651         check_added_monitors!(nodes[0], 1);
7652
7653         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7654         assert_eq!(events.len(), 1);
7655         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7656         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7657         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7658
7659         // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7660         // and then will wait a second random delay before failing the HTLC back:
7661         expect_pending_htlcs_forwardable!(nodes[1]);
7662         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
7663
7664         // Node 3 is expecting payment of 100_000 but received 10_000,
7665         // it should fail htlc like we didn't know the preimage.
7666         nodes[1].node.process_pending_htlc_forwards();
7667
7668         let events = nodes[1].node.get_and_clear_pending_msg_events();
7669         assert_eq!(events.len(), 1);
7670         let (update_fail_htlc, commitment_signed) = match events[0] {
7671                 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 } } => {
7672                         assert!(update_add_htlcs.is_empty());
7673                         assert!(update_fulfill_htlcs.is_empty());
7674                         assert_eq!(update_fail_htlcs.len(), 1);
7675                         assert!(update_fail_malformed_htlcs.is_empty());
7676                         assert!(update_fee.is_none());
7677                         (update_fail_htlcs[0].clone(), commitment_signed)
7678                 },
7679                 _ => panic!("Unexpected event"),
7680         };
7681         check_added_monitors!(nodes[1], 1);
7682
7683         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7684         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7685
7686         // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7687         let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7688         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(CHAN_CONFIRM_DEPTH));
7689         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7690 }
7691
7692 #[test]
7693 fn test_announce_disable_channels() {
7694         // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7695         // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7696
7697         let chanmon_cfgs = create_chanmon_cfgs(2);
7698         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7699         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7700         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7701
7702         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7703         create_announced_chan_between_nodes(&nodes, 1, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7704         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7705
7706         // Disconnect peers
7707         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7708         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7709
7710         nodes[0].node.timer_tick_occurred(); // Enabled -> DisabledStaged
7711         nodes[0].node.timer_tick_occurred(); // DisabledStaged -> Disabled
7712         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7713         assert_eq!(msg_events.len(), 3);
7714         let mut chans_disabled = HashMap::new();
7715         for e in msg_events {
7716                 match e {
7717                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7718                                 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7719                                 // Check that each channel gets updated exactly once
7720                                 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7721                                         panic!("Generated ChannelUpdate for wrong chan!");
7722                                 }
7723                         },
7724                         _ => panic!("Unexpected event"),
7725                 }
7726         }
7727         // Reconnect peers
7728         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
7729         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7730         assert_eq!(reestablish_1.len(), 3);
7731         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
7732         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7733         assert_eq!(reestablish_2.len(), 3);
7734
7735         // Reestablish chan_1
7736         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7737         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7738         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7739         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7740         // Reestablish chan_2
7741         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7742         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7743         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7744         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7745         // Reestablish chan_3
7746         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7747         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7748         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7749         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7750
7751         nodes[0].node.timer_tick_occurred();
7752         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7753         nodes[0].node.timer_tick_occurred();
7754         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7755         assert_eq!(msg_events.len(), 3);
7756         for e in msg_events {
7757                 match e {
7758                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7759                                 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7760                                 match chans_disabled.remove(&msg.contents.short_channel_id) {
7761                                         // Each update should have a higher timestamp than the previous one, replacing
7762                                         // the old one.
7763                                         Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7764                                         None => panic!("Generated ChannelUpdate for wrong chan!"),
7765                                 }
7766                         },
7767                         _ => panic!("Unexpected event"),
7768                 }
7769         }
7770         // Check that each channel gets updated exactly once
7771         assert!(chans_disabled.is_empty());
7772 }
7773
7774 #[test]
7775 fn test_bump_penalty_txn_on_revoked_commitment() {
7776         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7777         // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7778
7779         let chanmon_cfgs = create_chanmon_cfgs(2);
7780         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7781         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7782         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7783
7784         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7785
7786         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7787         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id())
7788                 .with_features(channelmanager::provided_invoice_features());
7789         let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000, 30);
7790         send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7791
7792         let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7793         // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7794         assert_eq!(revoked_txn[0].output.len(), 4);
7795         assert_eq!(revoked_txn[0].input.len(), 1);
7796         assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7797         let revoked_txid = revoked_txn[0].txid();
7798
7799         let mut penalty_sum = 0;
7800         for outp in revoked_txn[0].output.iter() {
7801                 if outp.script_pubkey.is_v0_p2wsh() {
7802                         penalty_sum += outp.value;
7803                 }
7804         }
7805
7806         // Connect blocks to change height_timer range to see if we use right soonest_timelock
7807         let header_114 = connect_blocks(&nodes[1], 14);
7808
7809         // Actually revoke tx by claiming a HTLC
7810         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7811         let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7812         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] });
7813         check_added_monitors!(nodes[1], 1);
7814
7815         // One or more justice tx should have been broadcast, check it
7816         let penalty_1;
7817         let feerate_1;
7818         {
7819                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7820                 assert_eq!(node_txn.len(), 2); // justice tx (broadcasted from ChannelMonitor) + local commitment tx
7821                 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7822                 assert_eq!(node_txn[0].output.len(), 1);
7823                 check_spends!(node_txn[0], revoked_txn[0]);
7824                 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7825                 feerate_1 = fee_1 * 1000 / node_txn[0].weight() as u64;
7826                 penalty_1 = node_txn[0].txid();
7827                 node_txn.clear();
7828         };
7829
7830         // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7831         connect_blocks(&nodes[1], 15);
7832         let mut penalty_2 = penalty_1;
7833         let mut feerate_2 = 0;
7834         {
7835                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7836                 assert_eq!(node_txn.len(), 1);
7837                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7838                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7839                         assert_eq!(node_txn[0].output.len(), 1);
7840                         check_spends!(node_txn[0], revoked_txn[0]);
7841                         penalty_2 = node_txn[0].txid();
7842                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7843                         assert_ne!(penalty_2, penalty_1);
7844                         let fee_2 = penalty_sum - node_txn[0].output[0].value;
7845                         feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7846                         // Verify 25% bump heuristic
7847                         assert!(feerate_2 * 100 >= feerate_1 * 125);
7848                         node_txn.clear();
7849                 }
7850         }
7851         assert_ne!(feerate_2, 0);
7852
7853         // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7854         connect_blocks(&nodes[1], 1);
7855         let penalty_3;
7856         let mut feerate_3 = 0;
7857         {
7858                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7859                 assert_eq!(node_txn.len(), 1);
7860                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7861                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7862                         assert_eq!(node_txn[0].output.len(), 1);
7863                         check_spends!(node_txn[0], revoked_txn[0]);
7864                         penalty_3 = node_txn[0].txid();
7865                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7866                         assert_ne!(penalty_3, penalty_2);
7867                         let fee_3 = penalty_sum - node_txn[0].output[0].value;
7868                         feerate_3 = fee_3 * 1000 / node_txn[0].weight() as u64;
7869                         // Verify 25% bump heuristic
7870                         assert!(feerate_3 * 100 >= feerate_2 * 125);
7871                         node_txn.clear();
7872                 }
7873         }
7874         assert_ne!(feerate_3, 0);
7875
7876         nodes[1].node.get_and_clear_pending_events();
7877         nodes[1].node.get_and_clear_pending_msg_events();
7878 }
7879
7880 #[test]
7881 fn test_bump_penalty_txn_on_revoked_htlcs() {
7882         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7883         // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7884
7885         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7886         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7887         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7888         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7889         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7890
7891         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7892         // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7893         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id()).with_features(channelmanager::provided_invoice_features());
7894         let scorer = test_utils::TestScorer::with_penalty(0);
7895         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7896         let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None,
7897                 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7898         let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7899         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id()).with_features(channelmanager::provided_invoice_features());
7900         let route = get_route(&nodes[1].node.get_our_node_id(), &payment_params, &nodes[1].network_graph.read_only(), None,
7901                 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7902         send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7903
7904         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7905         assert_eq!(revoked_local_txn[0].input.len(), 1);
7906         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7907
7908         // Revoke local commitment tx
7909         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7910
7911         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7912         // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7913         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] });
7914         check_closed_broadcast!(nodes[1], true);
7915         check_added_monitors!(nodes[1], 1);
7916         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7917         connect_blocks(&nodes[1], 49); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7918
7919         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
7920         assert_eq!(revoked_htlc_txn.len(), 3);
7921         check_spends!(revoked_htlc_txn[1], chan.3);
7922
7923         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7924         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7925         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7926
7927         assert_eq!(revoked_htlc_txn[2].input.len(), 1);
7928         assert_eq!(revoked_htlc_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7929         assert_eq!(revoked_htlc_txn[2].output.len(), 1);
7930         check_spends!(revoked_htlc_txn[2], revoked_local_txn[0]);
7931
7932         // Broadcast set of revoked txn on A
7933         let hash_128 = connect_blocks(&nodes[0], 40);
7934         let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7935         connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] });
7936         let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7937         connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[2].clone()] });
7938         let events = nodes[0].node.get_and_clear_pending_events();
7939         expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7940         match events.last().unwrap() {
7941                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7942                 _ => panic!("Unexpected event"),
7943         }
7944         let first;
7945         let feerate_1;
7946         let penalty_txn;
7947         {
7948                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7949                 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7950                 // Verify claim tx are spending revoked HTLC txn
7951
7952                 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7953                 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7954                 // which are included in the same block (they are broadcasted because we scan the
7955                 // transactions linearly and generate claims as we go, they likely should be removed in the
7956                 // future).
7957                 assert_eq!(node_txn[0].input.len(), 1);
7958                 check_spends!(node_txn[0], revoked_local_txn[0]);
7959                 assert_eq!(node_txn[1].input.len(), 1);
7960                 check_spends!(node_txn[1], revoked_local_txn[0]);
7961                 assert_eq!(node_txn[2].input.len(), 1);
7962                 check_spends!(node_txn[2], revoked_local_txn[0]);
7963
7964                 // Each of the three justice transactions claim a separate (single) output of the three
7965                 // available, which we check here:
7966                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7967                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7968                 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7969
7970                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7971                 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7972
7973                 // node_txn[3] is the local commitment tx broadcast just because (and somewhat in case of
7974                 // reorgs, though its not clear its ever worth broadcasting conflicting txn like this when
7975                 // a remote commitment tx has already been confirmed).
7976                 check_spends!(node_txn[3], chan.3);
7977
7978                 // node_txn[4] spends the revoked outputs from the revoked_htlc_txn (which only have one
7979                 // output, checked above).
7980                 assert_eq!(node_txn[4].input.len(), 2);
7981                 assert_eq!(node_txn[4].output.len(), 1);
7982                 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7983
7984                 first = node_txn[4].txid();
7985                 // Store both feerates for later comparison
7986                 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[4].output[0].value;
7987                 feerate_1 = fee_1 * 1000 / node_txn[4].weight() as u64;
7988                 penalty_txn = vec![node_txn[2].clone()];
7989                 node_txn.clear();
7990         }
7991
7992         // Connect one more block to see if bumped penalty are issued for HTLC txn
7993         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7994         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7995         let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7996         connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() });
7997         {
7998                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7999                 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
8000
8001                 check_spends!(node_txn[0], revoked_local_txn[0]);
8002                 check_spends!(node_txn[1], revoked_local_txn[0]);
8003                 // Note that these are both bogus - they spend outputs already claimed in block 129:
8004                 if node_txn[0].input[0].previous_output == revoked_htlc_txn[0].input[0].previous_output  {
8005                         assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
8006                 } else {
8007                         assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
8008                         assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
8009                 }
8010
8011                 node_txn.clear();
8012         };
8013
8014         // Few more blocks to confirm penalty txn
8015         connect_blocks(&nodes[0], 4);
8016         assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
8017         let header_144 = connect_blocks(&nodes[0], 9);
8018         let node_txn = {
8019                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8020                 assert_eq!(node_txn.len(), 1);
8021
8022                 assert_eq!(node_txn[0].input.len(), 2);
8023                 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[2]);
8024                 // Verify bumped tx is different and 25% bump heuristic
8025                 assert_ne!(first, node_txn[0].txid());
8026                 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[0].output[0].value;
8027                 let feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
8028                 assert!(feerate_2 * 100 > feerate_1 * 125);
8029                 let txn = vec![node_txn[0].clone()];
8030                 node_txn.clear();
8031                 txn
8032         };
8033         // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
8034         let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8035         connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn });
8036         connect_blocks(&nodes[0], 20);
8037         {
8038                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8039                 // We verify than no new transaction has been broadcast because previously
8040                 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
8041                 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
8042                 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
8043                 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
8044                 // up bumped justice generation.
8045                 assert_eq!(node_txn.len(), 0);
8046                 node_txn.clear();
8047         }
8048         check_closed_broadcast!(nodes[0], true);
8049         check_added_monitors!(nodes[0], 1);
8050 }
8051
8052 #[test]
8053 fn test_bump_penalty_txn_on_remote_commitment() {
8054         // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
8055         // we're able to claim outputs on remote commitment transaction before timelocks expiration
8056
8057         // Create 2 HTLCs
8058         // Provide preimage for one
8059         // Check aggregation
8060
8061         let chanmon_cfgs = create_chanmon_cfgs(2);
8062         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8063         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8064         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8065
8066         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8067         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
8068         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
8069
8070         // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
8071         let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
8072         assert_eq!(remote_txn[0].output.len(), 4);
8073         assert_eq!(remote_txn[0].input.len(), 1);
8074         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
8075
8076         // Claim a HTLC without revocation (provide B monitor with preimage)
8077         nodes[1].node.claim_funds(payment_preimage);
8078         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
8079         mine_transaction(&nodes[1], &remote_txn[0]);
8080         check_added_monitors!(nodes[1], 2);
8081         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
8082
8083         // One or more claim tx should have been broadcast, check it
8084         let timeout;
8085         let preimage;
8086         let preimage_bump;
8087         let feerate_timeout;
8088         let feerate_preimage;
8089         {
8090                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8091                 // 5 transactions including:
8092                 //   local commitment + HTLC-Success
8093                 //   preimage and timeout sweeps from remote commitment + preimage sweep bump
8094                 assert_eq!(node_txn.len(), 5);
8095                 assert_eq!(node_txn[0].input.len(), 1);
8096                 assert_eq!(node_txn[3].input.len(), 1);
8097                 assert_eq!(node_txn[4].input.len(), 1);
8098                 check_spends!(node_txn[0], remote_txn[0]);
8099                 check_spends!(node_txn[3], remote_txn[0]);
8100                 check_spends!(node_txn[4], remote_txn[0]);
8101
8102                 check_spends!(node_txn[1], chan.3); // local commitment
8103                 check_spends!(node_txn[2], node_txn[1]); // local HTLC-Success
8104
8105                 preimage = node_txn[0].txid();
8106                 let index = node_txn[0].input[0].previous_output.vout;
8107                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8108                 feerate_preimage = fee * 1000 / node_txn[0].weight() as u64;
8109
8110                 let (preimage_bump_tx, timeout_tx) = if node_txn[3].input[0].previous_output == node_txn[0].input[0].previous_output {
8111                         (node_txn[3].clone(), node_txn[4].clone())
8112                 } else {
8113                         (node_txn[4].clone(), node_txn[3].clone())
8114                 };
8115
8116                 preimage_bump = preimage_bump_tx;
8117                 check_spends!(preimage_bump, remote_txn[0]);
8118                 assert_eq!(node_txn[0].input[0].previous_output, preimage_bump.input[0].previous_output);
8119
8120                 timeout = timeout_tx.txid();
8121                 let index = timeout_tx.input[0].previous_output.vout;
8122                 let fee = remote_txn[0].output[index as usize].value - timeout_tx.output[0].value;
8123                 feerate_timeout = fee * 1000 / timeout_tx.weight() as u64;
8124
8125                 node_txn.clear();
8126         };
8127         assert_ne!(feerate_timeout, 0);
8128         assert_ne!(feerate_preimage, 0);
8129
8130         // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
8131         connect_blocks(&nodes[1], 15);
8132         {
8133                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8134                 assert_eq!(node_txn.len(), 1);
8135                 assert_eq!(node_txn[0].input.len(), 1);
8136                 assert_eq!(preimage_bump.input.len(), 1);
8137                 check_spends!(node_txn[0], remote_txn[0]);
8138                 check_spends!(preimage_bump, remote_txn[0]);
8139
8140                 let index = preimage_bump.input[0].previous_output.vout;
8141                 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
8142                 let new_feerate = fee * 1000 / preimage_bump.weight() as u64;
8143                 assert!(new_feerate * 100 > feerate_timeout * 125);
8144                 assert_ne!(timeout, preimage_bump.txid());
8145
8146                 let index = node_txn[0].input[0].previous_output.vout;
8147                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8148                 let new_feerate = fee * 1000 / node_txn[0].weight() as u64;
8149                 assert!(new_feerate * 100 > feerate_preimage * 125);
8150                 assert_ne!(preimage, node_txn[0].txid());
8151
8152                 node_txn.clear();
8153         }
8154
8155         nodes[1].node.get_and_clear_pending_events();
8156         nodes[1].node.get_and_clear_pending_msg_events();
8157 }
8158
8159 #[test]
8160 fn test_counterparty_raa_skip_no_crash() {
8161         // Previously, if our counterparty sent two RAAs in a row without us having provided a
8162         // commitment transaction, we would have happily carried on and provided them the next
8163         // commitment transaction based on one RAA forward. This would probably eventually have led to
8164         // channel closure, but it would not have resulted in funds loss. Still, our
8165         // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
8166         // check simply that the channel is closed in response to such an RAA, but don't check whether
8167         // we decide to punish our counterparty for revoking their funds (as we don't currently
8168         // implement that).
8169         let chanmon_cfgs = create_chanmon_cfgs(2);
8170         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8171         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8172         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8173         let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
8174
8175         let per_commitment_secret;
8176         let next_per_commitment_point;
8177         {
8178                 let mut guard = nodes[0].node.channel_state.lock().unwrap();
8179                 let keys = guard.by_id.get_mut(&channel_id).unwrap().get_signer();
8180
8181                 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
8182
8183                 // Make signer believe we got a counterparty signature, so that it allows the revocation
8184                 keys.get_enforcement_state().last_holder_commitment -= 1;
8185                 per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
8186
8187                 // Must revoke without gaps
8188                 keys.get_enforcement_state().last_holder_commitment -= 1;
8189                 keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
8190
8191                 keys.get_enforcement_state().last_holder_commitment -= 1;
8192                 next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
8193                         &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
8194         }
8195
8196         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
8197                 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
8198         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
8199         check_added_monitors!(nodes[1], 1);
8200         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
8201 }
8202
8203 #[test]
8204 fn test_bump_txn_sanitize_tracking_maps() {
8205         // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
8206         // verify we clean then right after expiration of ANTI_REORG_DELAY.
8207
8208         let chanmon_cfgs = create_chanmon_cfgs(2);
8209         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8210         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8211         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8212
8213         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8214         // Lock HTLC in both directions
8215         let (payment_preimage_1, _, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000);
8216         let (_, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000);
8217
8218         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
8219         assert_eq!(revoked_local_txn[0].input.len(), 1);
8220         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8221
8222         // Revoke local commitment tx
8223         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
8224
8225         // Broadcast set of revoked txn on A
8226         connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
8227         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[0], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
8228         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
8229
8230         mine_transaction(&nodes[0], &revoked_local_txn[0]);
8231         check_closed_broadcast!(nodes[0], true);
8232         check_added_monitors!(nodes[0], 1);
8233         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8234         let penalty_txn = {
8235                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8236                 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
8237                 check_spends!(node_txn[0], revoked_local_txn[0]);
8238                 check_spends!(node_txn[1], revoked_local_txn[0]);
8239                 check_spends!(node_txn[2], revoked_local_txn[0]);
8240                 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
8241                 node_txn.clear();
8242                 penalty_txn
8243         };
8244         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8245         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
8246         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8247         {
8248                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
8249                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
8250                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
8251         }
8252 }
8253
8254 #[test]
8255 fn test_pending_claimed_htlc_no_balance_underflow() {
8256         // Tests that if we have a pending outbound HTLC as well as a claimed-but-not-fully-removed
8257         // HTLC we will not underflow when we call `Channel::get_balance_msat()`.
8258         let chanmon_cfgs = create_chanmon_cfgs(2);
8259         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8260         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8261         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8262         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8263
8264         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_010_000);
8265         nodes[1].node.claim_funds(payment_preimage);
8266         expect_payment_claimed!(nodes[1], payment_hash, 1_010_000);
8267         check_added_monitors!(nodes[1], 1);
8268         let fulfill_ev = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8269
8270         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &fulfill_ev.update_fulfill_htlcs[0]);
8271         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
8272         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &fulfill_ev.commitment_signed);
8273         check_added_monitors!(nodes[0], 1);
8274         let (_raa, _cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
8275
8276         // At this point nodes[1] has received 1,010k msat (10k msat more than their reserve) and can
8277         // send an HTLC back (though it will go in the holding cell). Send an HTLC back and check we
8278         // can get our balance.
8279
8280         // Get a route from nodes[1] to nodes[0] by getting a route going the other way and then flip
8281         // the public key of the only hop. This works around ChannelDetails not showing the
8282         // almost-claimed HTLC as available balance.
8283         let (mut route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 10_000);
8284         route.payment_params = None; // This is all wrong, but unnecessary
8285         route.paths[0][0].pubkey = nodes[0].node.get_our_node_id();
8286         let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[0]);
8287         nodes[1].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
8288
8289         assert_eq!(nodes[1].node.list_channels()[0].balance_msat, 1_000_000);
8290 }
8291
8292 #[test]
8293 fn test_channel_conf_timeout() {
8294         // Tests that, for inbound channels, we give up on them if the funding transaction does not
8295         // confirm within 2016 blocks, as recommended by BOLT 2.
8296         let chanmon_cfgs = create_chanmon_cfgs(2);
8297         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8298         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8299         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8300
8301         let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8302
8303         // The outbound node should wait forever for confirmation:
8304         // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
8305         // copied here instead of directly referencing the constant.
8306         connect_blocks(&nodes[0], 2016);
8307         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8308
8309         // The inbound node should fail the channel after exactly 2016 blocks
8310         connect_blocks(&nodes[1], 2015);
8311         check_added_monitors!(nodes[1], 0);
8312         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8313
8314         connect_blocks(&nodes[1], 1);
8315         check_added_monitors!(nodes[1], 1);
8316         check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut);
8317         let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
8318         assert_eq!(close_ev.len(), 1);
8319         match close_ev[0] {
8320                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
8321                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8322                         assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
8323                 },
8324                 _ => panic!("Unexpected event"),
8325         }
8326 }
8327
8328 #[test]
8329 fn test_override_channel_config() {
8330         let chanmon_cfgs = create_chanmon_cfgs(2);
8331         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8332         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8333         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8334
8335         // Node0 initiates a channel to node1 using the override config.
8336         let mut override_config = UserConfig::default();
8337         override_config.channel_handshake_config.our_to_self_delay = 200;
8338
8339         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
8340
8341         // Assert the channel created by node0 is using the override config.
8342         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8343         assert_eq!(res.channel_flags, 0);
8344         assert_eq!(res.to_self_delay, 200);
8345 }
8346
8347 #[test]
8348 fn test_override_0msat_htlc_minimum() {
8349         let mut zero_config = UserConfig::default();
8350         zero_config.channel_handshake_config.our_htlc_minimum_msat = 0;
8351         let chanmon_cfgs = create_chanmon_cfgs(2);
8352         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8353         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
8354         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8355
8356         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
8357         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8358         assert_eq!(res.htlc_minimum_msat, 1);
8359
8360         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &res);
8361         let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8362         assert_eq!(res.htlc_minimum_msat, 1);
8363 }
8364
8365 #[test]
8366 fn test_channel_update_has_correct_htlc_maximum_msat() {
8367         // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
8368         // Bolt 7 specifies that if present `htlc_maximum_msat`:
8369         // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
8370         // 90% of the `channel_value`.
8371         // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
8372
8373         let mut config_30_percent = UserConfig::default();
8374         config_30_percent.channel_handshake_config.announced_channel = true;
8375         config_30_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
8376         let mut config_50_percent = UserConfig::default();
8377         config_50_percent.channel_handshake_config.announced_channel = true;
8378         config_50_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
8379         let mut config_95_percent = UserConfig::default();
8380         config_95_percent.channel_handshake_config.announced_channel = true;
8381         config_95_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
8382         let mut config_100_percent = UserConfig::default();
8383         config_100_percent.channel_handshake_config.announced_channel = true;
8384         config_100_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
8385
8386         let chanmon_cfgs = create_chanmon_cfgs(4);
8387         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8388         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[Some(config_30_percent), Some(config_50_percent), Some(config_95_percent), Some(config_100_percent)]);
8389         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8390
8391         let channel_value_satoshis = 100000;
8392         let channel_value_msat = channel_value_satoshis * 1000;
8393         let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
8394         let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
8395         let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
8396
8397         let (node_0_chan_update, node_1_chan_update, _, _)  = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value_satoshis, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8398         let (node_2_chan_update, node_3_chan_update, _, _)  = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, channel_value_satoshis, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8399
8400         // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
8401         // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
8402         assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, channel_value_50_percent_msat);
8403         // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
8404         // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
8405         assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, channel_value_30_percent_msat);
8406
8407         // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
8408         // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
8409         // `channel_value`.
8410         assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
8411         // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
8412         // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
8413         // `channel_value`.
8414         assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
8415 }
8416
8417 #[test]
8418 fn test_manually_accept_inbound_channel_request() {
8419         let mut manually_accept_conf = UserConfig::default();
8420         manually_accept_conf.manually_accept_inbound_channels = true;
8421         let chanmon_cfgs = create_chanmon_cfgs(2);
8422         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8423         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8424         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8425
8426         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8427         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8428
8429         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &res);
8430
8431         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8432         // accepting the inbound channel request.
8433         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8434
8435         let events = nodes[1].node.get_and_clear_pending_events();
8436         match events[0] {
8437                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8438                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
8439                 }
8440                 _ => panic!("Unexpected event"),
8441         }
8442
8443         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8444         assert_eq!(accept_msg_ev.len(), 1);
8445
8446         match accept_msg_ev[0] {
8447                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8448                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8449                 }
8450                 _ => panic!("Unexpected event"),
8451         }
8452
8453         nodes[1].node.force_close_broadcasting_latest_txn(&temp_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
8454
8455         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8456         assert_eq!(close_msg_ev.len(), 1);
8457
8458         let events = nodes[1].node.get_and_clear_pending_events();
8459         match events[0] {
8460                 Event::ChannelClosed { user_channel_id, .. } => {
8461                         assert_eq!(user_channel_id, 23);
8462                 }
8463                 _ => panic!("Unexpected event"),
8464         }
8465 }
8466
8467 #[test]
8468 fn test_manually_reject_inbound_channel_request() {
8469         let mut manually_accept_conf = UserConfig::default();
8470         manually_accept_conf.manually_accept_inbound_channels = true;
8471         let chanmon_cfgs = create_chanmon_cfgs(2);
8472         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8473         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8474         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8475
8476         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8477         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8478
8479         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &res);
8480
8481         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8482         // rejecting the inbound channel request.
8483         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8484
8485         let events = nodes[1].node.get_and_clear_pending_events();
8486         match events[0] {
8487                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8488                         nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
8489                 }
8490                 _ => panic!("Unexpected event"),
8491         }
8492
8493         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8494         assert_eq!(close_msg_ev.len(), 1);
8495
8496         match close_msg_ev[0] {
8497                 MessageSendEvent::HandleError { ref node_id, .. } => {
8498                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8499                 }
8500                 _ => panic!("Unexpected event"),
8501         }
8502         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
8503 }
8504
8505 #[test]
8506 fn test_reject_funding_before_inbound_channel_accepted() {
8507         // This tests that when `UserConfig::manually_accept_inbound_channels` is set to true, inbound
8508         // channels must to be manually accepted through `ChannelManager::accept_inbound_channel` by
8509         // the node operator before the counterparty sends a `FundingCreated` message. If a
8510         // `FundingCreated` message is received before the channel is accepted, it should be rejected
8511         // and the channel should be closed.
8512         let mut manually_accept_conf = UserConfig::default();
8513         manually_accept_conf.manually_accept_inbound_channels = true;
8514         let chanmon_cfgs = create_chanmon_cfgs(2);
8515         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8516         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8517         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8518
8519         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8520         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8521         let temp_channel_id = res.temporary_channel_id;
8522
8523         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &res);
8524
8525         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in the `msg_events`.
8526         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8527
8528         // Clear the `Event::OpenChannelRequest` event without responding to the request.
8529         nodes[1].node.get_and_clear_pending_events();
8530
8531         // Get the `AcceptChannel` message of `nodes[1]` without calling
8532         // `ChannelManager::accept_inbound_channel`, which generates a
8533         // `MessageSendEvent::SendAcceptChannel` event. The message is passed to `nodes[0]`
8534         // `handle_accept_channel`, which is required in order for `create_funding_transaction` to
8535         // succeed when `nodes[0]` is passed to it.
8536         let accept_chan_msg = {
8537                 let mut lock;
8538                 let channel = get_channel_ref!(&nodes[1], lock, temp_channel_id);
8539                 channel.get_accept_channel_message()
8540         };
8541         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_chan_msg);
8542
8543         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8544
8545         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8546         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8547
8548         // The `funding_created_msg` should be rejected by `nodes[1]` as it hasn't accepted the channel
8549         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8550
8551         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8552         assert_eq!(close_msg_ev.len(), 1);
8553
8554         let expected_err = "FundingCreated message received before the channel was accepted";
8555         match close_msg_ev[0] {
8556                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id, } => {
8557                         assert_eq!(msg.channel_id, temp_channel_id);
8558                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8559                         assert_eq!(msg.data, expected_err);
8560                 }
8561                 _ => panic!("Unexpected event"),
8562         }
8563
8564         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
8565 }
8566
8567 #[test]
8568 fn test_can_not_accept_inbound_channel_twice() {
8569         let mut manually_accept_conf = UserConfig::default();
8570         manually_accept_conf.manually_accept_inbound_channels = true;
8571         let chanmon_cfgs = create_chanmon_cfgs(2);
8572         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8573         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8574         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8575
8576         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8577         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8578
8579         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &res);
8580
8581         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8582         // accepting the inbound channel request.
8583         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8584
8585         let events = nodes[1].node.get_and_clear_pending_events();
8586         match events[0] {
8587                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8588                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
8589                         let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
8590                         match api_res {
8591                                 Err(APIError::APIMisuseError { err }) => {
8592                                         assert_eq!(err, "The channel isn't currently awaiting to be accepted.");
8593                                 },
8594                                 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
8595                                 Err(_) => panic!("Unexpected Error"),
8596                         }
8597                 }
8598                 _ => panic!("Unexpected event"),
8599         }
8600
8601         // Ensure that the channel wasn't closed after attempting to accept it twice.
8602         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8603         assert_eq!(accept_msg_ev.len(), 1);
8604
8605         match accept_msg_ev[0] {
8606                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8607                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8608                 }
8609                 _ => panic!("Unexpected event"),
8610         }
8611 }
8612
8613 #[test]
8614 fn test_can_not_accept_unknown_inbound_channel() {
8615         let chanmon_cfg = create_chanmon_cfgs(2);
8616         let node_cfg = create_node_cfgs(2, &chanmon_cfg);
8617         let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
8618         let nodes = create_network(2, &node_cfg, &node_chanmgr);
8619
8620         let unknown_channel_id = [0; 32];
8621         let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
8622         match api_res {
8623                 Err(APIError::ChannelUnavailable { err }) => {
8624                         assert_eq!(err, "Can't accept a channel that doesn't exist");
8625                 },
8626                 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
8627                 Err(_) => panic!("Unexpected Error"),
8628         }
8629 }
8630
8631 #[test]
8632 fn test_simple_mpp() {
8633         // Simple test of sending a multi-path payment.
8634         let chanmon_cfgs = create_chanmon_cfgs(4);
8635         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8636         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8637         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8638
8639         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).0.contents.short_channel_id;
8640         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features()).0.contents.short_channel_id;
8641         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features()).0.contents.short_channel_id;
8642         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features()).0.contents.short_channel_id;
8643
8644         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8645         let path = route.paths[0].clone();
8646         route.paths.push(path);
8647         route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8648         route.paths[0][0].short_channel_id = chan_1_id;
8649         route.paths[0][1].short_channel_id = chan_3_id;
8650         route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8651         route.paths[1][0].short_channel_id = chan_2_id;
8652         route.paths[1][1].short_channel_id = chan_4_id;
8653         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8654         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8655 }
8656
8657 #[test]
8658 fn test_preimage_storage() {
8659         // Simple test of payment preimage storage allowing no client-side storage to claim payments
8660         let chanmon_cfgs = create_chanmon_cfgs(2);
8661         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8662         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8663         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8664
8665         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).0.contents.short_channel_id;
8666
8667         {
8668                 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200).unwrap();
8669                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8670                 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8671                 check_added_monitors!(nodes[0], 1);
8672                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8673                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8674                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8675                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8676         }
8677         // Note that after leaving the above scope we have no knowledge of any arguments or return
8678         // values from previous calls.
8679         expect_pending_htlcs_forwardable!(nodes[1]);
8680         let events = nodes[1].node.get_and_clear_pending_events();
8681         assert_eq!(events.len(), 1);
8682         match events[0] {
8683                 Event::PaymentReceived { ref purpose, .. } => {
8684                         match &purpose {
8685                                 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
8686                                         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8687                                 },
8688                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
8689                         }
8690                 },
8691                 _ => panic!("Unexpected event"),
8692         }
8693 }
8694
8695 #[test]
8696 #[allow(deprecated)]
8697 fn test_secret_timeout() {
8698         // Simple test of payment secret storage time outs. After
8699         // `create_inbound_payment(_for_hash)_legacy` is removed, this test will be removed as well.
8700         let chanmon_cfgs = create_chanmon_cfgs(2);
8701         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8702         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8703         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8704
8705         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).0.contents.short_channel_id;
8706
8707         let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment_legacy(Some(100_000), 2).unwrap();
8708
8709         // We should fail to register the same payment hash twice, at least until we've connected a
8710         // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
8711         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8712                 assert_eq!(err, "Duplicate payment hash");
8713         } else { panic!(); }
8714         let mut block = {
8715                 let node_1_blocks = nodes[1].blocks.lock().unwrap();
8716                 Block {
8717                         header: BlockHeader {
8718                                 version: 0x2000000,
8719                                 prev_blockhash: node_1_blocks.last().unwrap().0.block_hash(),
8720                                 merkle_root: TxMerkleNode::all_zeros(),
8721                                 time: node_1_blocks.len() as u32 + 7200, bits: 42, nonce: 42 },
8722                         txdata: vec![],
8723                 }
8724         };
8725         connect_block(&nodes[1], &block);
8726         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8727                 assert_eq!(err, "Duplicate payment hash");
8728         } else { panic!(); }
8729
8730         // If we then connect the second block, we should be able to register the same payment hash
8731         // again (this time getting a new payment secret).
8732         block.header.prev_blockhash = block.header.block_hash();
8733         block.header.time += 1;
8734         connect_block(&nodes[1], &block);
8735         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2).unwrap();
8736         assert_ne!(payment_secret_1, our_payment_secret);
8737
8738         {
8739                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8740                 nodes[0].node.send_payment(&route, payment_hash, &Some(our_payment_secret)).unwrap();
8741                 check_added_monitors!(nodes[0], 1);
8742                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8743                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8744                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8745                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8746         }
8747         // Note that after leaving the above scope we have no knowledge of any arguments or return
8748         // values from previous calls.
8749         expect_pending_htlcs_forwardable!(nodes[1]);
8750         let events = nodes[1].node.get_and_clear_pending_events();
8751         assert_eq!(events.len(), 1);
8752         match events[0] {
8753                 Event::PaymentReceived { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret }, .. } => {
8754                         assert!(payment_preimage.is_none());
8755                         assert_eq!(payment_secret, our_payment_secret);
8756                         // We don't actually have the payment preimage with which to claim this payment!
8757                 },
8758                 _ => panic!("Unexpected event"),
8759         }
8760 }
8761
8762 #[test]
8763 fn test_bad_secret_hash() {
8764         // Simple test of unregistered payment hash/invalid payment secret handling
8765         let chanmon_cfgs = create_chanmon_cfgs(2);
8766         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8767         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8768         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8769
8770         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).0.contents.short_channel_id;
8771
8772         let random_payment_hash = PaymentHash([42; 32]);
8773         let random_payment_secret = PaymentSecret([43; 32]);
8774         let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2).unwrap();
8775         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8776
8777         // All the below cases should end up being handled exactly identically, so we macro the
8778         // resulting events.
8779         macro_rules! handle_unknown_invalid_payment_data {
8780                 ($payment_hash: expr) => {
8781                         check_added_monitors!(nodes[0], 1);
8782                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8783                         let payment_event = SendEvent::from_event(events.pop().unwrap());
8784                         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8785                         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8786
8787                         // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8788                         // again to process the pending backwards-failure of the HTLC
8789                         expect_pending_htlcs_forwardable!(nodes[1]);
8790                         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment{ payment_hash: $payment_hash }]);
8791                         check_added_monitors!(nodes[1], 1);
8792
8793                         // We should fail the payment back
8794                         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8795                         match events.pop().unwrap() {
8796                                 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8797                                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8798                                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8799                                 },
8800                                 _ => panic!("Unexpected event"),
8801                         }
8802                 }
8803         }
8804
8805         let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8806         // Error data is the HTLC value (100,000) and current block height
8807         let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8808
8809         // Send a payment with the right payment hash but the wrong payment secret
8810         nodes[0].node.send_payment(&route, our_payment_hash, &Some(random_payment_secret)).unwrap();
8811         handle_unknown_invalid_payment_data!(our_payment_hash);
8812         expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8813
8814         // Send a payment with a random payment hash, but the right payment secret
8815         nodes[0].node.send_payment(&route, random_payment_hash, &Some(our_payment_secret)).unwrap();
8816         handle_unknown_invalid_payment_data!(random_payment_hash);
8817         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8818
8819         // Send a payment with a random payment hash and random payment secret
8820         nodes[0].node.send_payment(&route, random_payment_hash, &Some(random_payment_secret)).unwrap();
8821         handle_unknown_invalid_payment_data!(random_payment_hash);
8822         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8823 }
8824
8825 #[test]
8826 fn test_update_err_monitor_lockdown() {
8827         // Our monitor will lock update of local commitment transaction if a broadcastion condition
8828         // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8829         // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
8830         //
8831         // This scenario may happen in a watchtower setup, where watchtower process a block height
8832         // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8833         // commitment at same time.
8834
8835         let chanmon_cfgs = create_chanmon_cfgs(2);
8836         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8837         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8838         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8839
8840         // Create some initial channel
8841         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8842         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8843
8844         // Rebalance the network to generate htlc in the two directions
8845         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8846
8847         // Route a HTLC from node 0 to node 1 (but don't settle)
8848         let (preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
8849
8850         // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8851         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8852         let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8853         let persister = test_utils::TestPersister::new();
8854         let watchtower = {
8855                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8856                 let mut w = test_utils::TestVecWriter(Vec::new());
8857                 monitor.write(&mut w).unwrap();
8858                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8859                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8860                 assert!(new_monitor == *monitor);
8861                 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);
8862                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8863                 watchtower
8864         };
8865         let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8866         let block = Block { header, txdata: vec![] };
8867         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8868         // transaction lock time requirements here.
8869         chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 0));
8870         watchtower.chain_monitor.block_connected(&block, 200);
8871
8872         // Try to update ChannelMonitor
8873         nodes[1].node.claim_funds(preimage);
8874         check_added_monitors!(nodes[1], 1);
8875         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
8876
8877         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8878         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8879         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8880         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8881                 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8882                         if let Err(_) =  watchtower.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8883                         if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8884                 } else { assert!(false); }
8885         } else { assert!(false); };
8886         // Our local monitor is in-sync and hasn't processed yet timeout
8887         check_added_monitors!(nodes[0], 1);
8888         let events = nodes[0].node.get_and_clear_pending_events();
8889         assert_eq!(events.len(), 1);
8890 }
8891
8892 #[test]
8893 fn test_concurrent_monitor_claim() {
8894         // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8895         // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8896         // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8897         // state N+1 confirms. Alice claims output from state N+1.
8898
8899         let chanmon_cfgs = create_chanmon_cfgs(2);
8900         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8901         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8902         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8903
8904         // Create some initial channel
8905         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8906         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8907
8908         // Rebalance the network to generate htlc in the two directions
8909         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8910
8911         // Route a HTLC from node 0 to node 1 (but don't settle)
8912         route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8913
8914         // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8915         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8916         let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8917         let persister = test_utils::TestPersister::new();
8918         let watchtower_alice = {
8919                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8920                 let mut w = test_utils::TestVecWriter(Vec::new());
8921                 monitor.write(&mut w).unwrap();
8922                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8923                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8924                 assert!(new_monitor == *monitor);
8925                 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);
8926                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8927                 watchtower
8928         };
8929         let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8930         let block = Block { header, txdata: vec![] };
8931         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8932         // transaction lock time requirements here.
8933         chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize((CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS) as usize, (block.clone(), 0));
8934         watchtower_alice.chain_monitor.block_connected(&block, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8935
8936         // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8937         {
8938                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8939                 assert_eq!(txn.len(), 2);
8940                 txn.clear();
8941         }
8942
8943         // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8944         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8945         let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8946         let persister = test_utils::TestPersister::new();
8947         let watchtower_bob = {
8948                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8949                 let mut w = test_utils::TestVecWriter(Vec::new());
8950                 monitor.write(&mut w).unwrap();
8951                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8952                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8953                 assert!(new_monitor == *monitor);
8954                 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);
8955                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8956                 watchtower
8957         };
8958         let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8959         watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8960
8961         // Route another payment to generate another update with still previous HTLC pending
8962         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8963         {
8964                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8965         }
8966         check_added_monitors!(nodes[1], 1);
8967
8968         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8969         assert_eq!(updates.update_add_htlcs.len(), 1);
8970         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8971         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8972                 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8973                         // Watchtower Alice should already have seen the block and reject the update
8974                         if let Err(_) =  watchtower_alice.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8975                         if let Ok(_) = watchtower_bob.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8976                         if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8977                 } else { assert!(false); }
8978         } else { assert!(false); };
8979         // Our local monitor is in-sync and hasn't processed yet timeout
8980         check_added_monitors!(nodes[0], 1);
8981
8982         //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8983         let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8984         watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8985
8986         // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8987         let bob_state_y;
8988         {
8989                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8990                 assert_eq!(txn.len(), 2);
8991                 bob_state_y = txn[0].clone();
8992                 txn.clear();
8993         };
8994
8995         // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8996         let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8997         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);
8998         {
8999                 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
9000                 assert_eq!(htlc_txn.len(), 1);
9001                 check_spends!(htlc_txn[0], bob_state_y);
9002         }
9003 }
9004
9005 #[test]
9006 fn test_pre_lockin_no_chan_closed_update() {
9007         // Test that if a peer closes a channel in response to a funding_created message we don't
9008         // generate a channel update (as the channel cannot appear on chain without a funding_signed
9009         // message).
9010         //
9011         // Doing so would imply a channel monitor update before the initial channel monitor
9012         // registration, violating our API guarantees.
9013         //
9014         // Previously, full_stack_target managed to hit this case by opening then closing a channel,
9015         // then opening a second channel with the same funding output as the first (which is not
9016         // rejected because the first channel does not exist in the ChannelManager) and closing it
9017         // before receiving funding_signed.
9018         let chanmon_cfgs = create_chanmon_cfgs(2);
9019         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9020         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9021         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9022
9023         // Create an initial channel
9024         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9025         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9026         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_chan_msg);
9027         let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9028         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_chan_msg);
9029
9030         // Move the first channel through the funding flow...
9031         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
9032
9033         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9034         check_added_monitors!(nodes[0], 0);
9035
9036         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9037         let channel_id = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
9038         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
9039         assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
9040         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "Hi".to_string() }, true);
9041 }
9042
9043 #[test]
9044 fn test_htlc_no_detection() {
9045         // This test is a mutation to underscore the detection logic bug we had
9046         // before #653. HTLC value routed is above the remaining balance, thus
9047         // inverting HTLC and `to_remote` output. HTLC will come second and
9048         // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
9049         // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
9050         // outputs order detection for correct spending children filtring.
9051
9052         let chanmon_cfgs = create_chanmon_cfgs(2);
9053         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9054         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9055         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9056
9057         // Create some initial channels
9058         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9059
9060         send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
9061         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
9062         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
9063         assert_eq!(local_txn[0].input.len(), 1);
9064         assert_eq!(local_txn[0].output.len(), 3);
9065         check_spends!(local_txn[0], chan_1.3);
9066
9067         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
9068         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
9069         connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] });
9070         // We deliberately connect the local tx twice as this should provoke a failure calling
9071         // this test before #653 fix.
9072         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);
9073         check_closed_broadcast!(nodes[0], true);
9074         check_added_monitors!(nodes[0], 1);
9075         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
9076         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1);
9077
9078         let htlc_timeout = {
9079                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
9080                 assert_eq!(node_txn[1].input.len(), 1);
9081                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9082                 check_spends!(node_txn[1], local_txn[0]);
9083                 node_txn[1].clone()
9084         };
9085
9086         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
9087         connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] });
9088         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
9089         expect_payment_failed!(nodes[0], our_payment_hash, false);
9090 }
9091
9092 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
9093         // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
9094         // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
9095         // Carol, Alice would be the upstream node, and Carol the downstream.)
9096         //
9097         // Steps of the test:
9098         // 1) Alice sends a HTLC to Carol through Bob.
9099         // 2) Carol doesn't settle the HTLC.
9100         // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
9101         // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
9102         // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
9103         //    but can't be claimed as Bob doesn't have yet knowledge of the preimage.
9104         // 5) Carol release the preimage to Bob off-chain.
9105         // 6) Bob claims the offered output on the broadcasted commitment.
9106         let chanmon_cfgs = create_chanmon_cfgs(3);
9107         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9108         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9109         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9110
9111         // Create some initial channels
9112         let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9113         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9114
9115         // Steps (1) and (2):
9116         // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
9117         let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
9118
9119         // Check that Alice's commitment transaction now contains an output for this HTLC.
9120         let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
9121         check_spends!(alice_txn[0], chan_ab.3);
9122         assert_eq!(alice_txn[0].output.len(), 2);
9123         check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
9124         assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9125         assert_eq!(alice_txn.len(), 2);
9126
9127         // Steps (3) and (4):
9128         // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
9129         // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
9130         let mut force_closing_node = 0; // Alice force-closes
9131         let mut counterparty_node = 1; // Bob if Alice force-closes
9132
9133         // Bob force-closes
9134         if !broadcast_alice {
9135                 force_closing_node = 1;
9136                 counterparty_node = 0;
9137         }
9138         nodes[force_closing_node].node.force_close_broadcasting_latest_txn(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id()).unwrap();
9139         check_closed_broadcast!(nodes[force_closing_node], true);
9140         check_added_monitors!(nodes[force_closing_node], 1);
9141         check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
9142         if go_onchain_before_fulfill {
9143                 let txn_to_broadcast = match broadcast_alice {
9144                         true => alice_txn.clone(),
9145                         false => get_local_commitment_txn!(nodes[1], chan_ab.2)
9146                 };
9147                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
9148                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
9149                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
9150                 if broadcast_alice {
9151                         check_closed_broadcast!(nodes[1], true);
9152                         check_added_monitors!(nodes[1], 1);
9153                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
9154                 }
9155                 assert_eq!(bob_txn.len(), 1);
9156                 check_spends!(bob_txn[0], chan_ab.3);
9157         }
9158
9159         // Step (5):
9160         // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
9161         // process of removing the HTLC from their commitment transactions.
9162         nodes[2].node.claim_funds(payment_preimage);
9163         check_added_monitors!(nodes[2], 1);
9164         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
9165
9166         let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
9167         assert!(carol_updates.update_add_htlcs.is_empty());
9168         assert!(carol_updates.update_fail_htlcs.is_empty());
9169         assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
9170         assert!(carol_updates.update_fee.is_none());
9171         assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
9172
9173         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
9174         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false, false);
9175         // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
9176         if !go_onchain_before_fulfill && broadcast_alice {
9177                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9178                 assert_eq!(events.len(), 1);
9179                 match events[0] {
9180                         MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
9181                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9182                         },
9183                         _ => panic!("Unexpected event"),
9184                 };
9185         }
9186         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
9187         // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
9188         // Carol<->Bob's updated commitment transaction info.
9189         check_added_monitors!(nodes[1], 2);
9190
9191         let events = nodes[1].node.get_and_clear_pending_msg_events();
9192         assert_eq!(events.len(), 2);
9193         let bob_revocation = match events[0] {
9194                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
9195                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
9196                         (*msg).clone()
9197                 },
9198                 _ => panic!("Unexpected event"),
9199         };
9200         let bob_updates = match events[1] {
9201                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
9202                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
9203                         (*updates).clone()
9204                 },
9205                 _ => panic!("Unexpected event"),
9206         };
9207
9208         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
9209         check_added_monitors!(nodes[2], 1);
9210         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
9211         check_added_monitors!(nodes[2], 1);
9212
9213         let events = nodes[2].node.get_and_clear_pending_msg_events();
9214         assert_eq!(events.len(), 1);
9215         let carol_revocation = match events[0] {
9216                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
9217                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
9218                         (*msg).clone()
9219                 },
9220                 _ => panic!("Unexpected event"),
9221         };
9222         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
9223         check_added_monitors!(nodes[1], 1);
9224
9225         // If this test requires the force-closed channel to not be on-chain until after the fulfill,
9226         // here's where we put said channel's commitment tx on-chain.
9227         let mut txn_to_broadcast = alice_txn.clone();
9228         if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
9229         if !go_onchain_before_fulfill {
9230                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
9231                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
9232                 // If Bob was the one to force-close, he will have already passed these checks earlier.
9233                 if broadcast_alice {
9234                         check_closed_broadcast!(nodes[1], true);
9235                         check_added_monitors!(nodes[1], 1);
9236                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
9237                 }
9238                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9239                 if broadcast_alice {
9240                         // In `connect_block()`, the ChainMonitor and ChannelManager are separately notified about a
9241                         // new block being connected. The ChannelManager being notified triggers a monitor update,
9242                         // which triggers broadcasting our commitment tx and an HTLC-claiming tx. The ChainMonitor
9243                         // being notified triggers the HTLC-claiming tx redundantly, resulting in 3 total txs being
9244                         // broadcasted.
9245                         assert_eq!(bob_txn.len(), 3);
9246                         check_spends!(bob_txn[1], chan_ab.3);
9247                 } else {
9248                         assert_eq!(bob_txn.len(), 2);
9249                         check_spends!(bob_txn[0], chan_ab.3);
9250                 }
9251         }
9252
9253         // Step (6):
9254         // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
9255         // broadcasted commitment transaction.
9256         {
9257                 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
9258                 if go_onchain_before_fulfill {
9259                         // Bob should now have an extra broadcasted tx, for the preimage-claiming transaction.
9260                         assert_eq!(bob_txn.len(), 2);
9261                 }
9262                 let script_weight = match broadcast_alice {
9263                         true => OFFERED_HTLC_SCRIPT_WEIGHT,
9264                         false => ACCEPTED_HTLC_SCRIPT_WEIGHT
9265                 };
9266                 // If Alice force-closed and Bob didn't receive her commitment transaction until after he
9267                 // received Carol's fulfill, he broadcasts the HTLC-output-claiming transaction first. Else if
9268                 // Bob force closed or if he found out about Alice's commitment tx before receiving Carol's
9269                 // fulfill, then he broadcasts the HTLC-output-claiming transaction second.
9270                 if broadcast_alice && !go_onchain_before_fulfill {
9271                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
9272                         assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
9273                 } else {
9274                         check_spends!(bob_txn[1], txn_to_broadcast[0]);
9275                         assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
9276                 }
9277         }
9278 }
9279
9280 #[test]
9281 fn test_onchain_htlc_settlement_after_close() {
9282         do_test_onchain_htlc_settlement_after_close(true, true);
9283         do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
9284         do_test_onchain_htlc_settlement_after_close(true, false);
9285         do_test_onchain_htlc_settlement_after_close(false, false);
9286 }
9287
9288 #[test]
9289 fn test_duplicate_chan_id() {
9290         // Test that if a given peer tries to open a channel with the same channel_id as one that is
9291         // already open we reject it and keep the old channel.
9292         //
9293         // Previously, full_stack_target managed to figure out that if you tried to open two channels
9294         // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
9295         // the existing channel when we detect the duplicate new channel, screwing up our monitor
9296         // updating logic for the existing channel.
9297         let chanmon_cfgs = create_chanmon_cfgs(2);
9298         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9299         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9300         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9301
9302         // Create an initial channel
9303         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9304         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9305         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_chan_msg);
9306         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id()));
9307
9308         // Try to create a second channel with the same temporary_channel_id as the first and check
9309         // that it is rejected.
9310         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_chan_msg);
9311         {
9312                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9313                 assert_eq!(events.len(), 1);
9314                 match events[0] {
9315                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9316                                 // Technically, at this point, nodes[1] would be justified in thinking both the
9317                                 // first (valid) and second (invalid) channels are closed, given they both have
9318                                 // the same non-temporary channel_id. However, currently we do not, so we just
9319                                 // move forward with it.
9320                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9321                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9322                         },
9323                         _ => panic!("Unexpected event"),
9324                 }
9325         }
9326
9327         // Move the first channel through the funding flow...
9328         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
9329
9330         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9331         check_added_monitors!(nodes[0], 0);
9332
9333         let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9334         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
9335         {
9336                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
9337                 assert_eq!(added_monitors.len(), 1);
9338                 assert_eq!(added_monitors[0].0, funding_output);
9339                 added_monitors.clear();
9340         }
9341         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9342
9343         let funding_outpoint = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
9344         let channel_id = funding_outpoint.to_channel_id();
9345
9346         // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
9347         // temporary one).
9348
9349         // First try to open a second channel with a temporary channel id equal to the txid-based one.
9350         // Technically this is allowed by the spec, but we don't support it and there's little reason
9351         // to. Still, it shouldn't cause any other issues.
9352         open_chan_msg.temporary_channel_id = channel_id;
9353         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_chan_msg);
9354         {
9355                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9356                 assert_eq!(events.len(), 1);
9357                 match events[0] {
9358                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9359                                 // Technically, at this point, nodes[1] would be justified in thinking both
9360                                 // channels are closed, but currently we do not, so we just move forward with it.
9361                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9362                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9363                         },
9364                         _ => panic!("Unexpected event"),
9365                 }
9366         }
9367
9368         // Now try to create a second channel which has a duplicate funding output.
9369         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9370         let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9371         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_chan_2_msg);
9372         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id()));
9373         create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
9374
9375         let funding_created = {
9376                 let mut a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
9377                 // Once we call `get_outbound_funding_created` the channel has a duplicate channel_id as
9378                 // another channel in the ChannelManager - an invalid state. Thus, we'd panic later when we
9379                 // try to create another channel. Instead, we drop the channel entirely here (leaving the
9380                 // channelmanager in a possibly nonsense state instead).
9381                 let mut as_chan = a_channel_lock.by_id.remove(&open_chan_2_msg.temporary_channel_id).unwrap();
9382                 let logger = test_utils::TestLogger::new();
9383                 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
9384         };
9385         check_added_monitors!(nodes[0], 0);
9386         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
9387         // At this point we'll try to add a duplicate channel monitor, which will be rejected, but
9388         // still needs to be cleared here.
9389         check_added_monitors!(nodes[1], 1);
9390
9391         // ...still, nodes[1] will reject the duplicate channel.
9392         {
9393                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9394                 assert_eq!(events.len(), 1);
9395                 match events[0] {
9396                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9397                                 // Technically, at this point, nodes[1] would be justified in thinking both
9398                                 // channels are closed, but currently we do not, so we just move forward with it.
9399                                 assert_eq!(msg.channel_id, channel_id);
9400                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9401                         },
9402                         _ => panic!("Unexpected event"),
9403                 }
9404         }
9405
9406         // finally, finish creating the original channel and send a payment over it to make sure
9407         // everything is functional.
9408         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
9409         {
9410                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9411                 assert_eq!(added_monitors.len(), 1);
9412                 assert_eq!(added_monitors[0].0, funding_output);
9413                 added_monitors.clear();
9414         }
9415
9416         let events_4 = nodes[0].node.get_and_clear_pending_events();
9417         assert_eq!(events_4.len(), 0);
9418         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9419         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9420
9421         let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9422         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9423         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9424         send_payment(&nodes[0], &[&nodes[1]], 8000000);
9425 }
9426
9427 #[test]
9428 fn test_error_chans_closed() {
9429         // Test that we properly handle error messages, closing appropriate channels.
9430         //
9431         // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
9432         // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
9433         // we can test various edge cases around it to ensure we don't regress.
9434         let chanmon_cfgs = create_chanmon_cfgs(3);
9435         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9436         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9437         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9438
9439         // Create some initial channels
9440         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9441         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9442         let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9443
9444         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9445         assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
9446         assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
9447
9448         // Closing a channel from a different peer has no effect
9449         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
9450         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9451
9452         // Closing one channel doesn't impact others
9453         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
9454         check_added_monitors!(nodes[0], 1);
9455         check_closed_broadcast!(nodes[0], false);
9456         check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
9457         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
9458         assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
9459         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);
9460         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);
9461
9462         // A null channel ID should close all channels
9463         let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9464         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
9465         check_added_monitors!(nodes[0], 2);
9466         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
9467         let events = nodes[0].node.get_and_clear_pending_msg_events();
9468         assert_eq!(events.len(), 2);
9469         match events[0] {
9470                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9471                         assert_eq!(msg.contents.flags & 2, 2);
9472                 },
9473                 _ => panic!("Unexpected event"),
9474         }
9475         match events[1] {
9476                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9477                         assert_eq!(msg.contents.flags & 2, 2);
9478                 },
9479                 _ => panic!("Unexpected event"),
9480         }
9481         // Note that at this point users of a standard PeerHandler will end up calling
9482         // peer_disconnected with no_connection_possible set to false, duplicating the
9483         // close-all-channels logic. That's OK, we don't want to end up not force-closing channels for
9484         // users with their own peer handling logic. We duplicate the call here, however.
9485         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9486         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9487
9488         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
9489         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9490         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9491 }
9492
9493 #[test]
9494 fn test_invalid_funding_tx() {
9495         // Test that we properly handle invalid funding transactions sent to us from a peer.
9496         //
9497         // Previously, all other major lightning implementations had failed to properly sanitize
9498         // funding transactions from their counterparties, leading to a multi-implementation critical
9499         // security vulnerability (though we always sanitized properly, we've previously had
9500         // un-released crashes in the sanitization process).
9501         //
9502         // Further, if the funding transaction is consensus-valid, confirms, and is later spent, we'd
9503         // previously have crashed in `ChannelMonitor` even though we closed the channel as bogus and
9504         // gave up on it. We test this here by generating such a transaction.
9505         let chanmon_cfgs = create_chanmon_cfgs(2);
9506         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9507         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9508         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9509
9510         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
9511         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id()));
9512         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id()));
9513
9514         let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
9515
9516         // Create a witness program which can be spent by a 4-empty-stack-elements witness and which is
9517         // 136 bytes long. This matches our "accepted HTLC preimage spend" matching, previously causing
9518         // a panic as we'd try to extract a 32 byte preimage from a witness element without checking
9519         // its length.
9520         let mut wit_program: Vec<u8> = channelmonitor::deliberately_bogus_accepted_htlc_witness_program();
9521         let wit_program_script: Script = wit_program.into();
9522         for output in tx.output.iter_mut() {
9523                 // Make the confirmed funding transaction have a bogus script_pubkey
9524                 output.script_pubkey = Script::new_v0_p2wsh(&wit_program_script.wscript_hash());
9525         }
9526
9527         nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
9528         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()));
9529         check_added_monitors!(nodes[1], 1);
9530
9531         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()));
9532         check_added_monitors!(nodes[0], 1);
9533
9534         let events_1 = nodes[0].node.get_and_clear_pending_events();
9535         assert_eq!(events_1.len(), 0);
9536
9537         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9538         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9539         nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9540
9541         let expected_err = "funding tx had wrong script/value or output index";
9542         confirm_transaction_at(&nodes[1], &tx, 1);
9543         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
9544         check_added_monitors!(nodes[1], 1);
9545         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9546         assert_eq!(events_2.len(), 1);
9547         if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9548                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9549                 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
9550                         assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
9551                 } else { panic!(); }
9552         } else { panic!(); }
9553         assert_eq!(nodes[1].node.list_channels().len(), 0);
9554
9555         // Now confirm a spend of the (bogus) funding transaction. As long as the witness is 5 elements
9556         // long the ChannelMonitor will try to read 32 bytes from the second-to-last element, panicing
9557         // as its not 32 bytes long.
9558         let mut spend_tx = Transaction {
9559                 version: 2i32, lock_time: PackedLockTime::ZERO,
9560                 input: tx.output.iter().enumerate().map(|(idx, _)| TxIn {
9561                         previous_output: BitcoinOutPoint {
9562                                 txid: tx.txid(),
9563                                 vout: idx as u32,
9564                         },
9565                         script_sig: Script::new(),
9566                         sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
9567                         witness: Witness::from_vec(channelmonitor::deliberately_bogus_accepted_htlc_witness())
9568                 }).collect(),
9569                 output: vec![TxOut {
9570                         value: 1000,
9571                         script_pubkey: Script::new(),
9572                 }]
9573         };
9574         check_spends!(spend_tx, tx);
9575         mine_transaction(&nodes[1], &spend_tx);
9576 }
9577
9578 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9579         // In the first version of the chain::Confirm interface, after a refactor was made to not
9580         // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9581         // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9582         // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9583         // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9584         // spending transaction until height N+1 (or greater). This was due to the way
9585         // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9586         // spending transaction at the height the input transaction was confirmed at, not whether we
9587         // should broadcast a spending transaction at the current height.
9588         // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9589         // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9590         // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9591         // until we learned about an additional block.
9592         //
9593         // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9594         // aren't broadcasting transactions too early (ie not broadcasting them at all).
9595         let chanmon_cfgs = create_chanmon_cfgs(3);
9596         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9597         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9598         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9599         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9600
9601         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9602         let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9603         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9604         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
9605         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9606
9607         nodes[1].node.force_close_broadcasting_latest_txn(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
9608         check_closed_broadcast!(nodes[1], true);
9609         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
9610         check_added_monitors!(nodes[1], 1);
9611         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9612         assert_eq!(node_txn.len(), 1);
9613
9614         let conf_height = nodes[1].best_block_info().1;
9615         if !test_height_before_timelock {
9616                 connect_blocks(&nodes[1], 24 * 6);
9617         }
9618         nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9619                 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9620         if test_height_before_timelock {
9621                 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9622                 // generate any events or broadcast any transactions
9623                 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9624                 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9625         } else {
9626                 // We should broadcast an HTLC transaction spending our funding transaction first
9627                 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9628                 assert_eq!(spending_txn.len(), 2);
9629                 assert_eq!(spending_txn[0], node_txn[0]);
9630                 check_spends!(spending_txn[1], node_txn[0]);
9631                 // We should also generate a SpendableOutputs event with the to_self output (as its
9632                 // timelock is up).
9633                 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9634                 assert_eq!(descriptor_spend_txn.len(), 1);
9635
9636                 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9637                 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9638                 // additional block built on top of the current chain.
9639                 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9640                         &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9641                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: channel_id }]);
9642                 check_added_monitors!(nodes[1], 1);
9643
9644                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9645                 assert!(updates.update_add_htlcs.is_empty());
9646                 assert!(updates.update_fulfill_htlcs.is_empty());
9647                 assert_eq!(updates.update_fail_htlcs.len(), 1);
9648                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9649                 assert!(updates.update_fee.is_none());
9650                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9651                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9652                 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9653         }
9654 }
9655
9656 #[test]
9657 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9658         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9659         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9660 }
9661
9662 #[test]
9663 fn test_forwardable_regen() {
9664         // Tests that if we reload a ChannelManager while forwards are pending we will regenerate the
9665         // PendingHTLCsForwardable event automatically, ensuring we don't forget to forward/receive
9666         // HTLCs.
9667         // We test it for both payment receipt and payment forwarding.
9668
9669         let chanmon_cfgs = create_chanmon_cfgs(3);
9670         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9671         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9672         let persister: test_utils::TestPersister;
9673         let new_chain_monitor: test_utils::TestChainMonitor;
9674         let nodes_1_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
9675         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9676         let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
9677         let chan_id_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
9678
9679         // First send a payment to nodes[1]
9680         let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
9681         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
9682         check_added_monitors!(nodes[0], 1);
9683
9684         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9685         assert_eq!(events.len(), 1);
9686         let payment_event = SendEvent::from_event(events.pop().unwrap());
9687         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9688         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9689
9690         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9691
9692         // Next send a payment which is forwarded by nodes[1]
9693         let (route_2, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 200_000);
9694         nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
9695         check_added_monitors!(nodes[0], 1);
9696
9697         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9698         assert_eq!(events.len(), 1);
9699         let payment_event = SendEvent::from_event(events.pop().unwrap());
9700         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9701         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9702
9703         // There is already a PendingHTLCsForwardable event "pending" so another one will not be
9704         // generated
9705         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
9706
9707         // Now restart nodes[1] and make sure it regenerates a single PendingHTLCsForwardable
9708         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9709         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9710
9711         let nodes_1_serialized = nodes[1].node.encode();
9712         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9713         let mut chan_1_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9714         get_monitor!(nodes[1], chan_id_1).write(&mut chan_0_monitor_serialized).unwrap();
9715         get_monitor!(nodes[1], chan_id_2).write(&mut chan_1_monitor_serialized).unwrap();
9716
9717         persister = test_utils::TestPersister::new();
9718         let keys_manager = &chanmon_cfgs[1].keys_manager;
9719         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);
9720         nodes[1].chain_monitor = &new_chain_monitor;
9721
9722         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
9723         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9724                 &mut chan_0_monitor_read, keys_manager).unwrap();
9725         assert!(chan_0_monitor_read.is_empty());
9726         let mut chan_1_monitor_read = &chan_1_monitor_serialized.0[..];
9727         let (_, mut chan_1_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9728                 &mut chan_1_monitor_read, keys_manager).unwrap();
9729         assert!(chan_1_monitor_read.is_empty());
9730
9731         let mut nodes_1_read = &nodes_1_serialized[..];
9732         let (_, nodes_1_deserialized_tmp) = {
9733                 let mut channel_monitors = HashMap::new();
9734                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
9735                 channel_monitors.insert(chan_1_monitor.get_funding_txo().0, &mut chan_1_monitor);
9736                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_1_read, ChannelManagerReadArgs {
9737                         default_config: UserConfig::default(),
9738                         keys_manager,
9739                         fee_estimator: node_cfgs[1].fee_estimator,
9740                         chain_monitor: nodes[1].chain_monitor,
9741                         tx_broadcaster: nodes[1].tx_broadcaster.clone(),
9742                         logger: nodes[1].logger,
9743                         channel_monitors,
9744                 }).unwrap()
9745         };
9746         nodes_1_deserialized = nodes_1_deserialized_tmp;
9747         assert!(nodes_1_read.is_empty());
9748
9749         assert!(nodes[1].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
9750         assert!(nodes[1].chain_monitor.watch_channel(chan_1_monitor.get_funding_txo().0, chan_1_monitor).is_ok());
9751         nodes[1].node = &nodes_1_deserialized;
9752         check_added_monitors!(nodes[1], 2);
9753
9754         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9755         // Note that nodes[1] and nodes[2] resend their channel_ready here since they haven't updated
9756         // the commitment state.
9757         reconnect_nodes(&nodes[1], &nodes[2], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9758
9759         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
9760
9761         expect_pending_htlcs_forwardable!(nodes[1]);
9762         expect_payment_received!(nodes[1], payment_hash, payment_secret, 100_000);
9763         check_added_monitors!(nodes[1], 1);
9764
9765         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9766         assert_eq!(events.len(), 1);
9767         let payment_event = SendEvent::from_event(events.pop().unwrap());
9768         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9769         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false);
9770         expect_pending_htlcs_forwardable!(nodes[2]);
9771         expect_payment_received!(nodes[2], payment_hash_2, payment_secret_2, 200_000);
9772
9773         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
9774         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage_2);
9775 }
9776
9777 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
9778         let chanmon_cfgs = create_chanmon_cfgs(2);
9779         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9780         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9781         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9782
9783         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9784
9785         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
9786                 .with_features(channelmanager::provided_invoice_features());
9787         let route = get_route!(nodes[0], payment_params, 10_000, TEST_FINAL_CLTV).unwrap();
9788
9789         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9790
9791         {
9792                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
9793                 check_added_monitors!(nodes[0], 1);
9794                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9795                 assert_eq!(events.len(), 1);
9796                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9797                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9798                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9799         }
9800         expect_pending_htlcs_forwardable!(nodes[1]);
9801         expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9802
9803         {
9804                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
9805                 check_added_monitors!(nodes[0], 1);
9806                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9807                 assert_eq!(events.len(), 1);
9808                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9809                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9810                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9811                 // At this point, nodes[1] would notice it has too much value for the payment. It will
9812                 // assume the second is a privacy attack (no longer particularly relevant
9813                 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9814                 // the first HTLC delivered above.
9815         }
9816
9817         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9818         nodes[1].node.process_pending_htlc_forwards();
9819
9820         if test_for_second_fail_panic {
9821                 // Now we go fail back the first HTLC from the user end.
9822                 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9823
9824                 let expected_destinations = vec![
9825                         HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9826                         HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9827                 ];
9828                 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1],  expected_destinations);
9829                 nodes[1].node.process_pending_htlc_forwards();
9830
9831                 check_added_monitors!(nodes[1], 1);
9832                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9833                 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9834
9835                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9836                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9837                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9838
9839                 let failure_events = nodes[0].node.get_and_clear_pending_events();
9840                 assert_eq!(failure_events.len(), 2);
9841                 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9842                 if let Event::PaymentPathFailed { .. } = failure_events[1] {} else { panic!(); }
9843         } else {
9844                 // Let the second HTLC fail and claim the first
9845                 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9846                 nodes[1].node.process_pending_htlc_forwards();
9847
9848                 check_added_monitors!(nodes[1], 1);
9849                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9850                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9851                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9852
9853                 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9854
9855                 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9856         }
9857 }
9858
9859 #[test]
9860 fn test_dup_htlc_second_fail_panic() {
9861         // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9862         // value for the payment, we'd fail back both HTLCs after generating a `PaymentReceived` event.
9863         // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9864         // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9865         do_test_dup_htlc_second_rejected(true);
9866 }
9867
9868 #[test]
9869 fn test_dup_htlc_second_rejected() {
9870         // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9871         // simply reject the second HTLC but are still able to claim the first HTLC.
9872         do_test_dup_htlc_second_rejected(false);
9873 }
9874
9875 #[test]
9876 fn test_inconsistent_mpp_params() {
9877         // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9878         // such HTLC and allow the second to stay.
9879         let chanmon_cfgs = create_chanmon_cfgs(4);
9880         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9881         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9882         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9883
9884         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9885         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9886         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9887         let chan_2_3 =create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9888
9889         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id())
9890                 .with_features(channelmanager::provided_invoice_features());
9891         let mut route = get_route!(nodes[0], payment_params, 15_000_000, TEST_FINAL_CLTV).unwrap();
9892         assert_eq!(route.paths.len(), 2);
9893         route.paths.sort_by(|path_a, _| {
9894                 // Sort the path so that the path through nodes[1] comes first
9895                 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
9896                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9897         });
9898         let payment_params_opt = Some(payment_params);
9899
9900         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9901
9902         let cur_height = nodes[0].best_block_info().1;
9903         let payment_id = PaymentId([42; 32]);
9904         {
9905                 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();
9906                 check_added_monitors!(nodes[0], 1);
9907
9908                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9909                 assert_eq!(events.len(), 1);
9910                 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9911         }
9912         assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9913
9914         {
9915                 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();
9916                 check_added_monitors!(nodes[0], 1);
9917
9918                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9919                 assert_eq!(events.len(), 1);
9920                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9921
9922                 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9923                 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9924
9925                 expect_pending_htlcs_forwardable!(nodes[2]);
9926                 check_added_monitors!(nodes[2], 1);
9927
9928                 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9929                 assert_eq!(events.len(), 1);
9930                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9931
9932                 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9933                 check_added_monitors!(nodes[3], 0);
9934                 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9935
9936                 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9937                 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9938                 // post-payment_secrets) and fail back the new HTLC.
9939         }
9940         expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9941         nodes[3].node.process_pending_htlc_forwards();
9942         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9943         nodes[3].node.process_pending_htlc_forwards();
9944
9945         check_added_monitors!(nodes[3], 1);
9946
9947         let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9948         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9949         commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9950
9951         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }]);
9952         check_added_monitors!(nodes[2], 1);
9953
9954         let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9955         nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9956         commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9957
9958         expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9959
9960         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();
9961         check_added_monitors!(nodes[0], 1);
9962
9963         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9964         assert_eq!(events.len(), 1);
9965         pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9966
9967         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9968 }
9969
9970 #[test]
9971 fn test_keysend_payments_to_public_node() {
9972         let chanmon_cfgs = create_chanmon_cfgs(2);
9973         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9974         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9975         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9976
9977         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9978         let network_graph = nodes[0].network_graph;
9979         let payer_pubkey = nodes[0].node.get_our_node_id();
9980         let payee_pubkey = nodes[1].node.get_our_node_id();
9981         let route_params = RouteParameters {
9982                 payment_params: PaymentParameters::for_keysend(payee_pubkey),
9983                 final_value_msat: 10000,
9984                 final_cltv_expiry_delta: 40,
9985         };
9986         let scorer = test_utils::TestScorer::with_penalty(0);
9987         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9988         let route = find_route(&payer_pubkey, &route_params, &network_graph, None, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
9989
9990         let test_preimage = PaymentPreimage([42; 32]);
9991         let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9992         check_added_monitors!(nodes[0], 1);
9993         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9994         assert_eq!(events.len(), 1);
9995         let event = events.pop().unwrap();
9996         let path = vec![&nodes[1]];
9997         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9998         claim_payment(&nodes[0], &path, test_preimage);
9999 }
10000
10001 #[test]
10002 fn test_keysend_payments_to_private_node() {
10003         let chanmon_cfgs = create_chanmon_cfgs(2);
10004         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10005         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10006         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10007
10008         let payer_pubkey = nodes[0].node.get_our_node_id();
10009         let payee_pubkey = nodes[1].node.get_our_node_id();
10010         nodes[0].node.peer_connected(&payee_pubkey, &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
10011         nodes[1].node.peer_connected(&payer_pubkey, &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
10012
10013         let _chan = create_chan_between_nodes(&nodes[0], &nodes[1], channelmanager::provided_init_features(), channelmanager::provided_init_features());
10014         let route_params = RouteParameters {
10015                 payment_params: PaymentParameters::for_keysend(payee_pubkey),
10016                 final_value_msat: 10000,
10017                 final_cltv_expiry_delta: 40,
10018         };
10019         let network_graph = nodes[0].network_graph;
10020         let first_hops = nodes[0].node.list_usable_channels();
10021         let scorer = test_utils::TestScorer::with_penalty(0);
10022         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
10023         let route = find_route(
10024                 &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
10025                 nodes[0].logger, &scorer, &random_seed_bytes
10026         ).unwrap();
10027
10028         let test_preimage = PaymentPreimage([42; 32]);
10029         let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
10030         check_added_monitors!(nodes[0], 1);
10031         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
10032         assert_eq!(events.len(), 1);
10033         let event = events.pop().unwrap();
10034         let path = vec![&nodes[1]];
10035         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
10036         claim_payment(&nodes[0], &path, test_preimage);
10037 }
10038
10039 #[test]
10040 fn test_double_partial_claim() {
10041         // Test what happens if a node receives a payment, generates a PaymentReceived event, the HTLCs
10042         // time out, the sender resends only some of the MPP parts, then the user processes the
10043         // PaymentReceived event, ensuring they don't inadvertently claim only part of the full payment
10044         // amount.
10045         let chanmon_cfgs = create_chanmon_cfgs(4);
10046         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
10047         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
10048         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
10049
10050         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
10051         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
10052         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
10053         create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
10054
10055         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
10056         assert_eq!(route.paths.len(), 2);
10057         route.paths.sort_by(|path_a, _| {
10058                 // Sort the path so that the path through nodes[1] comes first
10059                 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
10060                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
10061         });
10062
10063         send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 15_000_000, payment_hash, payment_secret);
10064         // nodes[3] has now received a PaymentReceived event...which it will take some (exorbitant)
10065         // amount of time to respond to.
10066
10067         // Connect some blocks to time out the payment
10068         connect_blocks(&nodes[3], TEST_FINAL_CLTV);
10069         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // To get the same height for sending later
10070
10071         let failed_destinations = vec![
10072                 HTLCDestination::FailedPayment { payment_hash },
10073                 HTLCDestination::FailedPayment { payment_hash },
10074         ];
10075         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations);
10076
10077         pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash);
10078
10079         // nodes[1] now retries one of the two paths...
10080         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
10081         check_added_monitors!(nodes[0], 2);
10082
10083         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
10084         assert_eq!(events.len(), 2);
10085         pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
10086
10087         // At this point nodes[3] has received one half of the payment, and the user goes to handle
10088         // that PaymentReceived event they got hours ago and never handled...we should refuse to claim.
10089         nodes[3].node.claim_funds(payment_preimage);
10090         check_added_monitors!(nodes[3], 0);
10091         assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
10092 }
10093
10094 fn do_test_partial_claim_before_restart(persist_both_monitors: bool) {
10095         // Test what happens if a node receives an MPP payment, claims it, but crashes before
10096         // persisting the ChannelManager. If `persist_both_monitors` is false, also crash after only
10097         // updating one of the two channels' ChannelMonitors. As a result, on startup, we'll (a) still
10098         // have the PaymentReceived event, (b) have one (or two) channel(s) that goes on chain with the
10099         // HTLC preimage in them, and (c) optionally have one channel that is live off-chain but does
10100         // not have the preimage tied to the still-pending HTLC.
10101         //
10102         // To get to the correct state, on startup we should propagate the preimage to the
10103         // still-off-chain channel, claiming the HTLC as soon as the peer connects, with the monitor
10104         // receiving the preimage without a state update.
10105         //
10106         // Further, we should generate a `PaymentClaimed` event to inform the user that the payment was
10107         // definitely claimed.
10108         let chanmon_cfgs = create_chanmon_cfgs(4);
10109         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
10110         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
10111
10112         let persister: test_utils::TestPersister;
10113         let new_chain_monitor: test_utils::TestChainMonitor;
10114         let nodes_3_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
10115
10116         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
10117
10118         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
10119         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
10120         let chan_id_persisted = create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
10121         let chan_id_not_persisted = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
10122
10123         // Create an MPP route for 15k sats, more than the default htlc-max of 10%
10124         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
10125         assert_eq!(route.paths.len(), 2);
10126         route.paths.sort_by(|path_a, _| {
10127                 // Sort the path so that the path through nodes[1] comes first
10128                 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
10129                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
10130         });
10131
10132         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
10133         check_added_monitors!(nodes[0], 2);
10134
10135         // Send the payment through to nodes[3] *without* clearing the PaymentReceived event
10136         let mut send_events = nodes[0].node.get_and_clear_pending_msg_events();
10137         assert_eq!(send_events.len(), 2);
10138         do_pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), send_events[0].clone(), true, false, None);
10139         do_pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), send_events[1].clone(), true, false, None);
10140
10141         // Now that we have an MPP payment pending, get the latest encoded copies of nodes[3]'s
10142         // monitors and ChannelManager, for use later, if we don't want to persist both monitors.
10143         let mut original_monitor = test_utils::TestVecWriter(Vec::new());
10144         if !persist_both_monitors {
10145                 for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
10146                         if outpoint.to_channel_id() == chan_id_not_persisted {
10147                                 assert!(original_monitor.0.is_empty());
10148                                 nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut original_monitor).unwrap();
10149                         }
10150                 }
10151         }
10152
10153         let mut original_manager = test_utils::TestVecWriter(Vec::new());
10154         nodes[3].node.write(&mut original_manager).unwrap();
10155
10156         expect_payment_received!(nodes[3], payment_hash, payment_secret, 15_000_000);
10157
10158         nodes[3].node.claim_funds(payment_preimage);
10159         check_added_monitors!(nodes[3], 2);
10160         expect_payment_claimed!(nodes[3], payment_hash, 15_000_000);
10161
10162         // Now fetch one of the two updated ChannelMonitors from nodes[3], and restart pretending we
10163         // crashed in between the two persistence calls - using one old ChannelMonitor and one new one,
10164         // with the old ChannelManager.
10165         let mut updated_monitor = test_utils::TestVecWriter(Vec::new());
10166         for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
10167                 if outpoint.to_channel_id() == chan_id_persisted {
10168                         assert!(updated_monitor.0.is_empty());
10169                         nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut updated_monitor).unwrap();
10170                 }
10171         }
10172         // If `persist_both_monitors` is set, get the second monitor here as well
10173         if persist_both_monitors {
10174                 for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
10175                         if outpoint.to_channel_id() == chan_id_not_persisted {
10176                                 assert!(original_monitor.0.is_empty());
10177                                 nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut original_monitor).unwrap();
10178                         }
10179                 }
10180         }
10181
10182         // Now restart nodes[3].
10183         persister = test_utils::TestPersister::new();
10184         let keys_manager = &chanmon_cfgs[3].keys_manager;
10185         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[3].chain_source), nodes[3].tx_broadcaster.clone(), nodes[3].logger, node_cfgs[3].fee_estimator, &persister, keys_manager);
10186         nodes[3].chain_monitor = &new_chain_monitor;
10187         let mut monitors = Vec::new();
10188         for mut monitor_data in [original_monitor, updated_monitor].iter() {
10189                 let (_, mut deserialized_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut &monitor_data.0[..], keys_manager).unwrap();
10190                 monitors.push(deserialized_monitor);
10191         }
10192
10193         let config = UserConfig::default();
10194         nodes_3_deserialized = {
10195                 let mut channel_monitors = HashMap::new();
10196                 for monitor in monitors.iter_mut() {
10197                         channel_monitors.insert(monitor.get_funding_txo().0, monitor);
10198                 }
10199                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut &original_manager.0[..], ChannelManagerReadArgs {
10200                         default_config: config,
10201                         keys_manager,
10202                         fee_estimator: node_cfgs[3].fee_estimator,
10203                         chain_monitor: nodes[3].chain_monitor,
10204                         tx_broadcaster: nodes[3].tx_broadcaster.clone(),
10205                         logger: nodes[3].logger,
10206                         channel_monitors,
10207                 }).unwrap().1
10208         };
10209         nodes[3].node = &nodes_3_deserialized;
10210
10211         for monitor in monitors {
10212                 // On startup the preimage should have been copied into the non-persisted monitor:
10213                 assert!(monitor.get_stored_preimages().contains_key(&payment_hash));
10214                 nodes[3].chain_monitor.watch_channel(monitor.get_funding_txo().0.clone(), monitor).unwrap();
10215         }
10216         check_added_monitors!(nodes[3], 2);
10217
10218         nodes[1].node.peer_disconnected(&nodes[3].node.get_our_node_id(), false);
10219         nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), false);
10220
10221         // During deserialization, we should have closed one channel and broadcast its latest
10222         // commitment transaction. We should also still have the original PaymentReceived event we
10223         // never finished processing.
10224         let events = nodes[3].node.get_and_clear_pending_events();
10225         assert_eq!(events.len(), if persist_both_monitors { 4 } else { 3 });
10226         if let Event::PaymentReceived { amount_msat: 15_000_000, .. } = events[0] { } else { panic!(); }
10227         if let Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } = events[1] { } else { panic!(); }
10228         if persist_both_monitors {
10229                 if let Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } = events[2] { } else { panic!(); }
10230         }
10231
10232         // On restart, we should also get a duplicate PaymentClaimed event as we persisted the
10233         // ChannelManager prior to handling the original one.
10234         if let Event::PaymentClaimed { payment_hash: our_payment_hash, amount_msat: 15_000_000, .. } =
10235                 events[if persist_both_monitors { 3 } else { 2 }]
10236         {
10237                 assert_eq!(payment_hash, our_payment_hash);
10238         } else { panic!(); }
10239
10240         assert_eq!(nodes[3].node.list_channels().len(), if persist_both_monitors { 0 } else { 1 });
10241         if !persist_both_monitors {
10242                 // If one of the two channels is still live, reveal the payment preimage over it.
10243
10244                 nodes[3].node.peer_connected(&nodes[2].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
10245                 let reestablish_1 = get_chan_reestablish_msgs!(nodes[3], nodes[2]);
10246                 nodes[2].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
10247                 let reestablish_2 = get_chan_reestablish_msgs!(nodes[2], nodes[3]);
10248
10249                 nodes[2].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish_1[0]);
10250                 get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, nodes[3].node.get_our_node_id());
10251                 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
10252
10253                 nodes[3].node.handle_channel_reestablish(&nodes[2].node.get_our_node_id(), &reestablish_2[0]);
10254
10255                 // Once we call `get_and_clear_pending_msg_events` the holding cell is cleared and the HTLC
10256                 // claim should fly.
10257                 let ds_msgs = nodes[3].node.get_and_clear_pending_msg_events();
10258                 check_added_monitors!(nodes[3], 1);
10259                 assert_eq!(ds_msgs.len(), 2);
10260                 if let MessageSendEvent::SendChannelUpdate { .. } = ds_msgs[1] {} else { panic!(); }
10261
10262                 let cs_updates = match ds_msgs[0] {
10263                         MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
10264                                 nodes[2].node.handle_update_fulfill_htlc(&nodes[3].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
10265                                 check_added_monitors!(nodes[2], 1);
10266                                 let cs_updates = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
10267                                 expect_payment_forwarded!(nodes[2], nodes[0], nodes[3], Some(1000), false, false);
10268                                 commitment_signed_dance!(nodes[2], nodes[3], updates.commitment_signed, false, true);
10269                                 cs_updates
10270                         }
10271                         _ => panic!(),
10272                 };
10273
10274                 nodes[0].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &cs_updates.update_fulfill_htlcs[0]);
10275                 commitment_signed_dance!(nodes[0], nodes[2], cs_updates.commitment_signed, false, true);
10276                 expect_payment_sent!(nodes[0], payment_preimage);
10277         }
10278 }
10279
10280 #[test]
10281 fn test_partial_claim_before_restart() {
10282         do_test_partial_claim_before_restart(false);
10283         do_test_partial_claim_before_restart(true);
10284 }
10285
10286 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
10287 #[derive(Clone, Copy, PartialEq)]
10288 enum ExposureEvent {
10289         /// Breach occurs at HTLC forwarding (see `send_htlc`)
10290         AtHTLCForward,
10291         /// Breach occurs at HTLC reception (see `update_add_htlc`)
10292         AtHTLCReception,
10293         /// Breach occurs at outbound update_fee (see `send_update_fee`)
10294         AtUpdateFeeOutbound,
10295 }
10296
10297 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool) {
10298         // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
10299         // policy.
10300         //
10301         // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
10302         // trimmed-to-dust HTLC outbound balance and this new payment as included on next
10303         // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
10304         // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
10305         // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
10306         // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
10307         // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
10308         // might be available again for HTLC processing once the dust bandwidth has cleared up.
10309
10310         let chanmon_cfgs = create_chanmon_cfgs(2);
10311         let mut config = test_default_channel_config();
10312         config.channel_config.max_dust_htlc_exposure_msat = 5_000_000; // default setting value
10313         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10314         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
10315         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10316
10317         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
10318         let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10319         open_channel.max_htlc_value_in_flight_msat = 50_000_000;
10320         open_channel.max_accepted_htlcs = 60;
10321         if on_holder_tx {
10322                 open_channel.dust_limit_satoshis = 546;
10323         }
10324         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_channel);
10325         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10326         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_channel);
10327
10328         let opt_anchors = false;
10329
10330         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
10331
10332         if on_holder_tx {
10333                 if let Some(mut chan) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&temporary_channel_id) {
10334                         chan.holder_dust_limit_satoshis = 546;
10335                 }
10336         }
10337
10338         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
10339         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()));
10340         check_added_monitors!(nodes[1], 1);
10341
10342         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()));
10343         check_added_monitors!(nodes[0], 1);
10344
10345         let (channel_ready, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
10346         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
10347         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
10348
10349         let dust_buffer_feerate = {
10350                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
10351                 let chan = chan_lock.by_id.get(&channel_id).unwrap();
10352                 chan.get_dust_buffer_feerate(None) as u64
10353         };
10354         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;
10355         let dust_outbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
10356
10357         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;
10358         let dust_inbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
10359
10360         let dust_htlc_on_counterparty_tx: u64 = 25;
10361         let dust_htlc_on_counterparty_tx_msat: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
10362
10363         if on_holder_tx {
10364                 if dust_outbound_balance {
10365                         // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
10366                         // Outbound dust balance: 4372 sats
10367                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
10368                         for i in 0..dust_outbound_htlc_on_holder_tx {
10369                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
10370                                 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at dust HTLC {}", i); }
10371                         }
10372                 } else {
10373                         // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
10374                         // Inbound dust balance: 4372 sats
10375                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
10376                         for _ in 0..dust_inbound_htlc_on_holder_tx {
10377                                 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
10378                         }
10379                 }
10380         } else {
10381                 if dust_outbound_balance {
10382                         // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
10383                         // Outbound dust balance: 5000 sats
10384                         for i in 0..dust_htlc_on_counterparty_tx {
10385                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
10386                                 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at dust HTLC {}", i); }
10387                         }
10388                 } else {
10389                         // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
10390                         // Inbound dust balance: 5000 sats
10391                         for _ in 0..dust_htlc_on_counterparty_tx {
10392                                 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
10393                         }
10394                 }
10395         }
10396
10397         let dust_overflow = dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx + 1);
10398         if exposure_breach_event == ExposureEvent::AtHTLCForward {
10399                 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 });
10400                 let mut config = UserConfig::default();
10401                 // With default dust exposure: 5000 sats
10402                 if on_holder_tx {
10403                         let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * (dust_outbound_htlc_on_holder_tx + 1);
10404                         let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * dust_inbound_htlc_on_holder_tx + dust_outbound_htlc_on_holder_tx_msat;
10405                         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_config.max_dust_htlc_exposure_msat)));
10406                 } else {
10407                         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_config.max_dust_htlc_exposure_msat)));
10408                 }
10409         } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
10410                 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 });
10411                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
10412                 check_added_monitors!(nodes[1], 1);
10413                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
10414                 assert_eq!(events.len(), 1);
10415                 let payment_event = SendEvent::from_event(events.remove(0));
10416                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
10417                 // With default dust exposure: 5000 sats
10418                 if on_holder_tx {
10419                         // Outbound dust balance: 6399 sats
10420                         let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
10421                         let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
10422                         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_config.max_dust_htlc_exposure_msat), 1);
10423                 } else {
10424                         // Outbound dust balance: 5200 sats
10425                         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_config.max_dust_htlc_exposure_msat), 1);
10426                 }
10427         } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
10428                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 2_500_000);
10429                 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at update_fee-swallowed HTLC", ); }
10430                 {
10431                         let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
10432                         *feerate_lock = *feerate_lock * 10;
10433                 }
10434                 nodes[0].node.timer_tick_occurred();
10435                 check_added_monitors!(nodes[0], 1);
10436                 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);
10437         }
10438
10439         let _ = nodes[0].node.get_and_clear_pending_msg_events();
10440         let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
10441         added_monitors.clear();
10442 }
10443
10444 #[test]
10445 fn test_max_dust_htlc_exposure() {
10446         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true);
10447         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true);
10448         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true);
10449         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false);
10450         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false);
10451         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false);
10452         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true);
10453         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false);
10454         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true);
10455         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false);
10456         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false);
10457         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true);
10458 }
10459
10460 #[test]
10461 fn test_non_final_funding_tx() {
10462         let chanmon_cfgs = create_chanmon_cfgs(2);
10463         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10464         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10465         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10466
10467         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
10468         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10469         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_channel_message);
10470         let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10471         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_channel_message);
10472
10473         let best_height = nodes[0].node.best_block.read().unwrap().height();
10474
10475         let chan_id = *nodes[0].network_chan_count.borrow();
10476         let events = nodes[0].node.get_and_clear_pending_events();
10477         let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::Script::new(), sequence: Sequence(1), witness: Witness::from_vec(vec!(vec!(1))) };
10478         assert_eq!(events.len(), 1);
10479         let mut tx = match events[0] {
10480                 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
10481                         // Timelock the transaction _beyond_ the best client height + 2.
10482                         Transaction { version: chan_id as i32, lock_time: PackedLockTime(best_height + 3), input: vec![input], output: vec![TxOut {
10483                                 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
10484                         }]}
10485                 },
10486                 _ => panic!("Unexpected event"),
10487         };
10488         // Transaction should fail as it's evaluated as non-final for propagation.
10489         match nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()) {
10490                 Err(APIError::APIMisuseError { err }) => {
10491                         assert_eq!(format!("Funding transaction absolute timelock is non-final"), err);
10492                 },
10493                 _ => panic!()
10494         }
10495
10496         // However, transaction should be accepted if it's in a +2 headroom from best block.
10497         tx.lock_time = PackedLockTime(tx.lock_time.0 - 1);
10498         assert!(nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
10499         get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
10500 }